![](/img/trans.png)
[英]How to split a string of multiple words into a list with strings of a certain number of words?
[英]sort a list of strings by the number of words in the string
我有这样的字符串列表:
mylist = ["superduperlongstring", "a short string", "the middle"]
我想对这种方式进行排序,以使单词数量最多的字符串排在首位,即
mylist = ["a short string", "the middle", "superduperlongstring"]
这有点棘手,因为如果我按长度排序
mylist.sort(key = len)
我回到了开始的地方。
有没有人遇到过一个优雅的解决方案? 谢谢。
假设单词之间用空格分隔, str.split
带任何参数的调用str.split
返回字符串包含的单词的列表:
>>> "superduperlongstring".split()
['superduperlongstring']
>>> "a short string".split()
['a', 'short', 'string']
>>> "the middle".split()
['the', 'middle']
>>>
因此,可以根据这些列表的长度对mylist
进行排序,以获得所需的输出:
>>> 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
,如上所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.