按字符串中的单词数对字符串列表进行排序

编程入门 行业动态 更新时间:2024-10-26 08:26:27
本文介绍了按字符串中的单词数对字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个这样的字符串列表:

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.

更多推荐

按字符串中的单词数对字符串列表进行排序

本文发布于:2023-10-18 03:22:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502931.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   词数   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!