按多个属性对列表进行排序? [英] Sort a list by multiple attributes?
本文介绍了按多个属性对列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表列表:
[[12, 'tall', 'blue', 1],
[2, 'short', 'red', 9],
[4, 'tall', 'blue', 13]]
如果我想按一个元素(例如,高/短元素)进行排序,则可以通过s = sorted(s, key = itemgetter(1))
进行.
If I wanted to sort by one element, say the tall/short element, I could do it via s = sorted(s, key = itemgetter(1))
.
如果我想按长/短和颜色同时进行排序,我可以进行两次排序,每个元素一次,但是有一种更快的方法吗?
If I wanted to sort by both tall/short and colour, I could do the sort twice, once for each element, but is there a quicker way?
推荐答案
键可以是返回元组的函数:
A key can be a function that returns a tuple:
s = sorted(s, key = lambda x: (x[1], x[2]))
或者您可以使用itemgetter
来实现相同目的(更快,并且避免了Python函数调用):
Or you can achieve the same using itemgetter
(which is faster and avoids a Python function call):
import operator
s = sorted(s, key = operator.itemgetter(1, 2))
请注意,在这里您可以使用sort
而不是sorted
然后重新分配:
And notice that here you can use sort
instead of using sorted
and then reassigning:
s.sort(key = operator.itemgetter(1, 2))
这篇关于按多个属性对列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文