sort a 2D list first by 1st column and then by 2nd column

前提是你 提交于 2020-07-02 18:22:26

问题


I am trying to find a nice way to sort a 2d list , first by the 1st value , and then by the 2nd value.

I think an example will be the best If I have a list

[[1,4],
[2,7],
[10,1],
[1,2],
[10,6]
[2,1]]

I want that is will be sorted like this

[[1,2],
[1,4],
[2,1],
[2,7],
[10,1],
[10,6]]

回答1:


l=[[1,4],
[2,7],
[10,1],
[1,2],
[10,6],
[2,1]]
print sorted(l,key=lambda x: (x[0],x[1])) # use lambda to sort by "x[0]"-> first element of the sublists or x[1] -> second element, if its a tie
[[1, 2], [1, 4], [2, 1], [2, 7], [10, 1], [10, 6]]

Or simply sorted(l) of l.sort() as your elements sort naturally.

A better example would be to sort by the second value only:

print sorted(l,key=lambda x: (x[1]))
[[10, 1], [2, 1], [1, 2], [1, 4], [10, 6], [2, 7]]


来源:https://stackoverflow.com/questions/25046306/sort-a-2d-list-first-by-1st-column-and-then-by-2nd-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!