按字符串中的单词数对字符串列表进行排序 [英] sort a list of strings by the number of words in the string
问题描述
我有一个这样的字符串列表:
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)
我回到了起点.
有没有人遇到过一个优雅的解决方案?谢谢.
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']
>>>
因此,您可以根据以下列表的长度对mylist
进行排序,以获得所需的输出:
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']
>>>
您还需要将list.sort
的reverse
参数设置为True
,如上所示.
You will also need to set the reverse
parameter of list.sort
to True
, as shown above.
这篇关于按字符串中的单词数对字符串列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!