根据字符串的长度对Python列表进行排序 [英] Sorting Python list based on the length of the string

查看:52
本文介绍了根据字符串的长度对Python列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据字符串长度对字符串列表进行排序.我尝试按如下方式使用排序,但它似乎没有给我正确的结果.

I want to sort a list of strings based on the string length. I tried to use sort as follows, but it doesn't seem to give me correct result.

xs = ['dddd','a','bb','ccc']
print xs
xs.sort(lambda x,y: len(x) < len(y))
print xs

['dddd', 'a', 'bb', 'ccc']
['dddd', 'a', 'bb', 'ccc']

可能有什么问题?

推荐答案

当您将 lambda 传递给 sort 时,您需要返回一个整数,而不是一个布尔值.因此,您的代码应改为如下所示:

When you pass a lambda to sort, you need to return an integer, not a boolean. So your code should instead read as follows:

xs.sort(lambda x,y: cmp(len(x), len(y)))

请注意,cmp 是一个内置函数,使得 cmp(x, y) 如果 x 小于 y 返回 -1,如果 x 等于 y<返回 0/code>,如果 x 大于 y,则为 1.

Note that cmp is a builtin function such that cmp(x, y) returns -1 if x is less than y, 0 if x is equal to y, and 1 if x is greater than y.

当然,您也可以使用 key 参数:

Of course, you can instead use the key parameter:

xs.sort(key=lambda s: len(s))

这告诉 sort 方法根据键函数返回的内容进行排序.

This tells the sort method to order based on whatever the key function returns.

感谢下面的 balpha 和 Ruslan 指出您可以直接将 len 作为关键参数传递给函数,从而消除对 lambda 的需要:

Thanks to balpha and Ruslan below for pointing out that you can just pass len directly as the key parameter to the function, thus eliminating the need for a lambda:

xs.sort(key=len)

正如 Ruslan 在下面指出的,您还可以使用内置的 sorted 函数而不是 list.sort 方法,它创建一个新列表而不是就地排序现有列表:

And as Ruslan points out below, you can also use the built-in sorted function rather than the list.sort method, which creates a new list rather than sorting the existing one in-place:

print(sorted(xs, key=len))

这篇关于根据字符串的长度对Python列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆