I have a list of strings that have 2 dashes separating text like:
Wednesday-Morning-Go bowling
Sunday-Really late at night-Sleep
July-Noon-BBQ
I'd like to sort the list in alphabetical order in python by the last part of the string--the 2nd dash and on. Is there a way to do this in python? E.g. this is what I would want the list to look like after sorting.
July-Noon-BBQ
Wednesday-Morning-Go bowling
Sunday-Really late at night-Sleep
(I'm using Python 2.6.)
You can use the key
attribute to list.sort()
:
a = ["Wednesday-Morning-Go bowling", "Sunday-Really late at night-Sleep",
"July-Noon-BBQ"]
a.sort(key=lambda x: x.split("-", 2)[-1])
print a
prints
['July-Noon-BBQ', 'Wednesday-Morning-Go bowling', 'Sunday-Really late at night-Sleep']
Note that the split()
call allows for more than 2 dashes. Every dash after the second one will be ignored and included in the third part.
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