1. lamda关键字设置排序
s = [('john', 'A', 15), ('jane', 'C', 10), ('dave', 'B', 12)]
# 用lamda关键字设置排序key
print(sorted(s, key=lambda x: x[0]))
print(sorted(s, key=lambda x: x[1]))
print(sorted(s, key=lambda x: x[2], reverse=True))
[('dave', 'B', 12), ('jane', 'C', 10), ('john', 'A', 15)]
[('john', 'A', 15), ('dave', 'B', 12), ('jane', 'C', 10)]
[('john', 'A', 15), ('dave', 'B', 12), ('jane', 'C', 10)]
2. operator 函数 加快排序
from operator import itemgetter
s = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'A', 10), ]
print(sorted(s, key=itemgetter(0)))
print(sorted(s, key=itemgetter(2, 1))) # 属性2先排序,再以属性1排序
print(sorted(s, key=itemgetter(1, 2))) # 属性1先排序,再以属性2排序
[('dave', 'A', 10), ('jane', 'B', 12), ('john', 'A', 15)]
[('dave', 'A', 10), ('jane', 'B', 12), ('john', 'A', 15)]
[('dave', 'A', 10), ('john', 'A', 15), ('jane', 'B', 12)]
网友评论