python:按子列表中的项目对列表列表进行排序 [英] python: sort a list of lists by an item in the sublist
本文介绍了python:按子列表中的项目对列表列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含用户和得分的列表列表,如下所示:
I have a list of lists that contains users and scores as follows:
[["user1", 100], ["user2", 234], ["user3", 131]...]
我想生成一个列表,该列表按分数按降序对用户进行排序:
I want to produce a list that sorts the users by score in declining order:
[["user2", 234], ["user3", 131], ["user1", 100]...]
我应该怎么做这种事情?
How might I go about doing this kind of sort?
推荐答案
>>> 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]]
这篇关于python:按子列表中的项目对列表列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文