I have an array that containts elements out of words. I want to have a sorted list at the end. How do I do this in python? Thanks
Eg:
JavaScript
x
2
1
SETACTION = "forever", "for one and", "for two"
2
=>
JavaScript
1
2
1
SETACTION = "for one and", "for two", "forever"
2
Advertisement
Answer
You can use a lambda that will sort first by reverse length then by length of the first element:
JavaScript
1
3
1
>>> sorted(SETACTION,key=lambda s:(-len(s), len(s.partition(' ')[0])))
2
['for one and', 'for two', 'forever']
3