如何在python sorted(list)中指定2个键? [英] How to specify 2 keys in python sorted(list)?
本文介绍了如何在python sorted(list)中指定2个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何首先按key=len
然后按key=str
对字符串列表进行排序?
我已经尝试了以下方法,但是没有给我想要的排序方式:
How do I sort a list of strings by key=len
first then by key=str
?
I've tried the following but it's not giving me the desired sort:
>>> ls = ['foo','bar','foobar','barbar']
>>>
>>> for i in sorted(ls):
... print i
...
bar
barbar
foo
foobar
>>>
>>> for i in sorted(ls, key=len):
... print i
...
foo
bar
foobar
barbar
>>>
>>> for i in sorted(ls, key=str):
... print i
...
bar
barbar
foo
foobar
我需要得到:
bar
foo
barbar
foobar
推荐答案
定义一个返回一个元组的键函数,其中第一项为len(str)
,第二项为字符串本身.然后在字典上比较元组.也就是说,首先将长度进行比较;然后再对长度进行比较.如果它们相等,则将字符串进行比较.
Define a key function that returns a tuple in which the first item is len(str)
and the second one is the string itself. Tuples are then compared lexicographically. That is, first the lengths are compared; if they are equal then the strings get compared.
In [1]: ls = ['foo','bar','foobar','barbar']
In [2]: sorted(ls, key=lambda s: (len(s), s))
Out[2]: ['bar', 'foo', 'barbar', 'foobar']
这篇关于如何在python sorted(list)中指定2个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文