When I was reading this answer https://stackoverflow.com/a/9841401/5175044 to a question on removing duplicates from a string, I couldn't understand what the index
attribute meant in
''.join(sorted(set(foo), key=foo.index))
I did this example run:
foo = "Wicked long string"
>>> "".join(sorted(set(foo),key = foo.index))
'Wicked longstr'
>>> "".join(sorted(set(foo)))
' Wcdegiklnorst'
which leads me to think that it helps in keeping the order of the characters.
As mentioned by others Pythons sorted()
function and the sort()
method of a list provides the key
parameter to specify a function to be called on each list element prior to making comparisons.
The key thing is that this key
parameter is a function object that takes when it is called only one argument and returns exactly one value which is used for the sorting.
A anonymous "lambda" function is often used for this purpose, since its definition does not include a return
statement and therefor always contains an one expression which is returned.
For instance
>>> myKey = lambda e: id(e)
creates an (anonymous) function object
>>> type(myKey)
<class 'function'>
which takes one argument and returns a value and would therefore be a valid key
for sorting.
If you want to call the myKey
function object now you would simply do this:
>>> myKey(42)
503732608
To solve your problem you could create a lambda function as key
which takes an element and returns its index in the foo
string to keep the order of the characters:
>>> foo = "Wicked long string"
>>> "".join(sorted(set(foo), key = lambda e: foo.index(e)))
'Wicked longstr'
On the other hand -- since foo.index
is a function object itself which takes one argument and returns one value -- you could pass this object instead to the sorted()
function and by-pass the lambda definition:
>>> "".join(sorted(set(foo),key = foo.index))
'Wicked longstr'
Hope this helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With