I have a list of strings as such:
mylist = ["superduperlongstring", "a short string", "the middle"]
I want to sort this in such a way that the string with the largest number of words is first, ie,
mylist = ["a short string", "the middle", "superduperlongstring"]
Its a bit tricky, since if I sort in place by length
mylist.sort(key = len)
I'm back where I started.
Has anyone come across a graceful solution to this? Thanks.
Assuming that words are separated by whitespace, calling str.split
with no arguments returns a list of the words that a string contains:
>>> "superduperlongstring".split()
['superduperlongstring']
>>> "a short string".split()
['a', 'short', 'string']
>>> "the middle".split()
['the', 'middle']
>>>
Therefore, you can get the output you want by sorting mylist
based off of the length of these lists:
>>> mylist = ["superduperlongstring", "a short string", "the middle"]
>>> mylist.sort(key=lambda x: len(x.split()), reverse=True)
>>> mylist
['a short string', 'the middle', 'superduperlongstring']
>>>
You will also need to set the reverse
parameter of list.sort
to True
, as shown above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.