当待排序列表的元素由多字段构成时,我们可以通过sorted(iterable,key,reverse)的参数key来制定我们根据那个字段对列表元素进行排序。
key=lambda 元素: 元素[字段索引]
例如:想对元素第二个字段排序,则
key=lambda y: y[1] 备注:这里y可以是任意字母,等同key=lambda x: x[1]
看几个简单的例子。
items.sort(key=lambda x:x[1],reverse=True)
print(items)
原列表:
[('while', 1), ('there', 2), ('is', 2), ('life', 1), ('hope', 1)]
输出:
[('there', 2), ('is', 2), ('while', 1), ('life', 1), ('hope', 1)]