我有一个包含用户和分数的列表列表,如下所示:
[["user1", 100], ["user2", 234], ["user3", 131]...]
我想生成一个列表,按分数按降序对用户进行排序:
[["user2", 234], ["user3", 131], ["user1", 100]...]
我该怎么做这种事情?
>>> li = [["user1", 100], ["user2", 234], ["user3", 131]]
>>>
>>> import operator
>>>
>>> sorted(li, key=operator.itemgetter(1)) # Ascending order
[['user1', 100], ['user3', 131], ['user2', 234]]
>>> sorted(li, key=operator.itemgetter(1), reverse=True) # Reverse Sort
[['user2', 234], ['user3', 131], ['user1', 100]]
您可以通过传递键和反向来自定义排序行为。sorted
将返回一个新列表。如果需要就地排序,请使用list.sort
.
>>> a = [["user1", 100], ["user2", 234], ["user3", 131]]
>>> sorted(a, key=lambda x: x[1], reverse=True)
[['user2', 234], ['user3', 131], ['user1', 100]]
sorted接受可选key
函数和反向参数。
>>> sorted([["user1", 100], ["user2", 234], ["user3", 131]], key=lambda x: x[1], reverse=True)
[['user2', 234], ['user3', 131], ['user1', 100]]
l = [["user1", 100], ["user2", 234], ["user3", 131]]
l.sort(lambda x, y: x[1])