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

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

问题描述

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

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,如果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在下面指出的那样,您还可以使用内置的已排序函数而不是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天全站免登陆