1

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"

3 Answers 3

1

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']
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

forever has the length of 1, for two the length of 2
Well then the accepted answer is incorrect. You're trying to sort by number of words.
1

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.