person = [{'name': 'zhangsan', 'age': 37},
{'name': 'lisi', 'age': 40},
{'name': 'wangwu', 'age': 43},
{'name': 'zhangsan', 'age': 22}]
print(person)
# 先按姓名升序排序,姓名相同的按年龄降序排序
print(sorted(person, key=lambda x: (x['name'], -x['age'])))
from operator import itemgetter
phonebook = {'linda': '7750', 'Bob': '9345', 'Carol': '5834'}
print(sorted(phonebook.items(), key=itemgetter(1)))
print(sorted(phonebook.items(), key=itemgetter(0)))
from operator import itemgetter
gameresult = [['Bob', 95.0, 'A'],
['Alan', 86.0, 'B'],
['Mandy', 95.0, 'A'],
['Bob', 59.0, 'E']]
# 按姓名升序,姓名相同按分数升序
print(sorted(gameresult, key=itemgetter(0, 1)))
# 按分数升序,分数相同的按姓名升序
print(sorted(gameresult, key=itemgetter(1, 0)))
# 按等级升序,等级相同的按姓名升序
print(sorted(gameresult, key=itemgetter(2, 0)))
from operator import itemgetter
gameresult = [{'name': 'Bob', 'wins': 10, 'lpsses': 3},
{'name': 'David', 'wins': 3, 'losses': 5},
{'name': 'Carol', 'wins': 10, 'losses': 5},
{'name': 'Patty', 'wins': 9, 'losses': 3}]
# 按'wins'升序,该值相同则按'name'升序排序
print(sorted(gameresult, key=itemgetter('wins', 'name')))
# 根据另外一个列表的值来对当前列表元素进行排序
list1 = ["what", "I'm", "sorting", "by"]
list2 = ["something", "else", "to", "sort"]
pairs = zip(list1, list2)
print(sorted(pairs))
print(sorted(list2, key=lambda item: list1[list2.index(item)]))
有一个整数列表,要求调整元素顺序,把奇数放在前面,偶数放在后面
from random import randint
x = [randint(1, 100) for _ in range(20)]
print(x)
print(sorted(x, key=lambda item: item % 2 == 0))