我有一个这样的字符串列表:
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.
推荐答案假定单词由空格分隔,请调用 str.split 返回字符串包含的单词的列表:
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.
更多推荐
按字符串中的单词数对字符串列表进行排序
发布评论