Python内置函数sorted()高级排序用法

可以结合Python内置函数sorted()从入门到精通来看一些稍微基础的排序用法。

>>> from operator import itemgetter

>>> gameresult = [['Bob', 95.0, 'A'],

['Alan', 86.0, 'C'],

['Mandy', 83.5, 'A'],

['Rob', 89.3, 'E']]

#按子列表第3个元素进行升序排序

>>> sorted(gameresult, key=itemgetter(2))

[['Bob', 95.0, 'A'], ['Mandy', 83.5, 'A'], ['Alan', 86.0, 'C'], ['Rob', 89.3, 'E']]

#按第3个元素升序,然后按第1个升序

>>> sorted(gameresult, key=itemgetter(2, 0))

[['Bob', 95.0, 'A'], ['Mandy', 83.5, 'A'], ['Alan', 86.0, 'C'], ['Rob', 89.3, 'E']]

>>> sorted(gameresult, key=itemgetter(2, 0), reverse=True)

[['Rob', 89.3, 'E'], ['Alan', 86.0, 'C'], ['Mandy', 83.5, 'A'], ['Bob', 95.0, 'A']]

>>> 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}]

#按’wins’升序,该值相同的按’name’升序排序

>>> sorted(gameresult, key=itemgetter('wins', 'name'))

[{'wins': 3, 'rating': 57.0, 'name': 'David', 'losses': 5}, {'wins': 4, 'rating': 57.0, 'name': 'Carol', 'losses': 5}, {'wins': 9, 'rating': 72.8, 'name': 'Patty', 'losses': 3}, {'wins': 10, 'rating': 75.0, 'name': 'Bob', 'losses': 3}]

#以一个列表内容为依据,对另一个列表内容进行排序

>>> list1 = ["what", "I'm", "sorting", "by"]

>>> list2 = ["something", "else", "to", "sort"]

#把两个列表中的对应位置元素配对

>>> pairs = zip(list1, list2)

>>> [item[1] for item in sorted(pairs, key=lambda x:x[0], reverse=True)]

['something', 'to', 'sort', 'else']

下一篇
举报

扫码关注云+社区

领取腾讯云代金券