# python内置函数sorted()深入

#使用key来指定排序依据，先按姓名升序排序，姓名相同的按年龄降序排序
>>> persons = [{'name':'xuzm', 'age':10}, {'name':'xuzm2', 'age':20}, {'name':'xuzm4', 'age':40}, {'name':'xuzm3', 'age':30}]

>>> persons
[{'name': 'xuzm', 'age': 10}, {'name': 'xuzm2', 'age': 20}, {'name': 'xuzm4', 'age': 40}, {'name': 'xuzm3', 'age': 30}]
>>> print(sorted(persons, key=lambda x:(x['name'], -x['age'])))
[{'name': 'xuzm', 'age': 10}, {'name': 'xuzm2', 'age': 20}, {'name': 'xuzm3', 'age': 30}, {'name': 'xuzm4', 'age': 40}]

>>> phonebook = {'xuzm':'123', 'xuzm2':'456', 'xuzm3':'789'}
>>> from operator import itemgetter
>>> sorted(phonebook.items(), key=itemgetter(1))    #按字典元素的值默认进行升序排列
[('xuzm', '123'), ('xuzm2', '456'), ('xuzm3', '789')]
>>> sorted(phonebook.items(), key=itemgetter(0),reverse=True)     #按字典中元素的键进行降序排序
[('xuzm3', '789'), ('xuzm2', '456'), ('xuzm', '123')]

>>> gameresult = [['Bob', 95.0, 'A'], ['Alan', 86.0, 'C'], ['Mandy', 83.5, 'A'], ['Rob', 89.3, 'E']]
>>> sorted(gameresult, key=itemgetter(0, 1))    #按姓名升序排列，姓名相同的按分数进行升序排列
[['Alan', 86.0, 'C'], ['Bob', 95.0, 'A'], ['Mandy', 83.5, 'A'], ['Rob', 89.3, 'E']]
>>> sorted(gameresult, key=itemgetter(1, 0))    #按分数进行升序排列，分数相同的按姓名进行升序排列
[['Mandy', 83.5, 'A'], ['Alan', 86.0, 'C'], ['Rob', 89.3, 'E'], ['Bob', 95.0, 'A']]
>>> sorted(gameresult, key=itemgetter(2, 0))    #按等级升序排列，等级相同的按姓名进行升序排列
[['Bob', 95.0, 'A'], ['Mandy', 83.5, 'A'], ['Alan', 86.0, 'C'], ['Rob', 89.3, 'E']]
>>> gameresult = [{'name':'Bob', 'wins':10, 'losses':3, 'rating':75.0},
{'name':'David', 'wins':3, 'losses':5, 'rating':57.0},
{'name':'Carol', 'wins':4, 'losses':5, 'rating':57.0},
{'name':'Patty', 'wins':9, 'losses':3, 'rating':72.8}]
>>> sorted(gameresult, key=itemgetter('wins', 'name'))    #按wins排列，wins相同的按name惊进行排列
[{'name': 'David', 'wins': 3, 'losses': 5, 'rating': 57.0}, {'name': 'Carol', 'wins': 4, 'losses': 5, 'rating': 57.0}, {'name': 'Patty', 'wins': 9, 'losses': 3, 'rating': 72.8}, {'name': 'Bob', 'wins': 10, 'losses': 3, 'rating': 75.0}]

>>> list1 = ["what", "I'm", "sorting", "by"]
>>> list2 = ["something", "else", "to", "sort"]
>>> pairs = zip(list1, list2)    #用zip对象压缩
>>> pairs = sorted(pairs)    #新列表按照list1进行排序
>>> pairs
[("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
>>> result = [x[1] for x in pairs]    #按新列表中list1的顺序筛选出新列表中的list2部分
>>> result
['else', 'sort', 'to', 'something']

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120