简体   繁体   English

在Python中对2D列表进行排序

[英]Sorting a 2D list in Python

I have a 2D list: 我有一个2D列表:

mylist = [[9,7, 2, 2], [1,8, 2, 2], [2,9, 2, 2]]

Using a sort function, the list is sorted like this: 使用排序功能,列表的排序方式如下:

[[1, 8, 2, 2], [2, 9, 2, 2], [9, 7, 2, 2]]

But I want to sort this list like this: 但我想这样排序这个列表:

[[9, 7, 2, 2],[1, 8, 2, 2], [2, 9, 2, 2]]

in which instead of the first digit of the list, I want to sort it by the last digit, like using a sort function - it sorted by the first digit of the list. 而不是列表的第一个数字,我想按最后一个数字排序,比如使用排序函数 - 它按列表的第一个数字排序。 I want to sort it by the last digit like 7 is smaller than 8 and 9 so 7 comes first. 我想按最后一个数字排序,比如7小于8和9,所以7先来。

use sorted() with lambda Try this 使用sorted()lambda试试这个

In [1]: a=[[9, 7, 2, 2],[1, 8, 2, 2], [2, 9, 2, 2]]
In [4]: sorted(a,key=lambda a:a[::-1])
Out[4]: [[9, 7, 2, 2], [1, 8, 2, 2], [2, 9, 2, 2]]

You can try: 你可以试试:

sorted(a,key=lambda a:list(reversed(a)))

Output: 输出:

[[9, 7, 2, 2], [1, 8, 2, 2], [2, 9, 2, 2]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM