python: sort a list of lists by an item in the sublist
本问题已经有最佳答案,请猛点这里访问。
我有一个包含用户和分数的列表,如下所示:
1 | [["user1", 100], ["user2", 234], ["user3", 131]...] |
我要生成一个列表,按得分降序对用户排序:
1 | [["user2", 234], ["user3", 131], ["user1", 100]...] |
号
我该怎么做呢?
1 2 3 4 5 6 7 8 9 | >>> 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]] |
您可以通过传递键和反转来定制排序行为。
1 2 3 | >>> a = [["user1", 100], ["user2", 234], ["user3", 131]] >>> sorted(a, key=lambda x: x[1], reverse=True) [['user2', 234], ['user3', 131], ['user1', 100]] |
。
1 2 | l = [["user1", 100], ["user2", 234], ["user3", 131]] l.sort(lambda x, y: x[1]) |
号
排序接受可选的
1 2 | >>> sorted([["user1", 100], ["user2", 234], ["user3", 131]], key=lambda x: x[1], reverse=True) [['user2', 234], ['user3', 131], ['user1', 100]] |