sort string arrays of texts by length python
Question:
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"
Answers:
You can easily achieve that using sorted
with a custom key
and reverse=True
like so:
>>> sorted(SETACTION, key=len, reverse=True)
['for one and', 'forever', 'for two']
Do keep in mind forever
and for<space>two
are the same length.
Just to go a little further: if you want strings of the same length to be sorted alphabetically, you can write a custom sorting function; for example:
SETACTION = "forever", "for one and", "for two"
def my_sorting_func(x):
return -len(x),x
# It will sort first by -length (thus by descending length) then by alphabetical order
print(sorted(SETACTION, key=my_sorting_func))
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']
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"
You can easily achieve that using sorted
with a custom key
and reverse=True
like so:
>>> sorted(SETACTION, key=len, reverse=True)
['for one and', 'forever', 'for two']
Do keep in mind forever
and for<space>two
are the same length.
Just to go a little further: if you want strings of the same length to be sorted alphabetically, you can write a custom sorting function; for example:
SETACTION = "forever", "for one and", "for two"
def my_sorting_func(x):
return -len(x),x
# It will sort first by -length (thus by descending length) then by alphabetical order
print(sorted(SETACTION, key=my_sorting_func))
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']