Skip to content
Advertisement

sort string arrays of texts by length python

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:

SETACTION = "forever", "for one and",  "for two"

=>

SETACTION = "for one and", "for two", "forever"

Advertisement

Answer

You can use a lambda that will sort first by reverse length then by length of the first element:

>>> sorted(SETACTION,key=lambda s:(-len(s), len(s.partition(' ')[0])))
['for one and', 'for two', 'forever']
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement