list排序
根据list的不同元素排序
>>> pokemon = [
... ('Charmander', 'Fire', 52),
... ('Blastoise', 'Water', 83),
... ('Beedrill', 'Poison', 90),
... ]
>>> sorted(pokemon, key=lambda x: x[2])
[('Charmander', 'Fire', 52),
('Blastoise', 'Water', 83),
('Beedrill', 'Poison', 90)]
自定义函数排序
>>> import functools
def compare(x, y):
if x[0] > y[0]:
return 1
elif x[0] < y[0]:
return -1
elif x[0] == y[0]:
if x[1] >= y[1]:
return 1
elif x[1] < y[1]:
return -1
a = Solution()
A = [(2,3), (1,5), (3,1), (3, 5), (2,9)]
cmp_func = functools.cmp_to_key(compare)
sorted_list = sorted(A, key=cmp_func)
print(sorted_list)
[(1, 5), (2, 3), (2, 9), (3, 1), (3, 5)]
第一个元素降序排序,第二个元素升序排序
>>>
>>> sorted(l, key = lambda x: (-x[0], x[1]))
[(3, 'aaa'), (3, 'ab'), (2, 'aaa'), (1, 'bbbb')]