Python 如何对xy坐标列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37111798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort a list of x-y coordinates
提问by gegese
I need to sort a list of [x,y]
coordinates that looks like this:
我需要对如下所示的[x,y]
坐标列表进行排序:
list = [[1,2],[0,2],[2,1],[1,1],[2,2],[2,0],[0,1],[1,0],[0,0]]
The pattern I'm looking for after sorting is:
排序后我正在寻找的模式是:
[x,y]
coordinate shall be sorted by y
first and then by x
. The new list should look like:
[x,y]
坐标应按y
first排序,然后按 排序x
。新列表应如下所示:
list = [[0,0],[1,0],[2,0],[0,1],[1,1],[2,1],[0,2],[1,2],[2,2]]
I can't figure out how to do it and would appreciate some help.
我不知道该怎么做,希望得到一些帮助。
回答by AKS
use sorted
with key:
sorted
与键一起使用:
>>> my_list = [[1,2],[0,2],[2,1],[1,1],[2,2],[2,0],[0,1],[1,0],[0,0]]
>>> sorted(my_list , key=lambda k: [k[1], k[0]])
[[0, 0], [1, 0], [2, 0], [0, 1], [1, 1], [2, 1], [0, 2], [1, 2], [2, 2]]
It will first sort on the y value and if that's equal then it will sort on the x value.
它将首先对 y 值进行排序,如果相等,则它将对 x 值进行排序。
I would also advise to not use list
as a variable because it is a built-in data structure.
我还建议不要list
用作变量,因为它是内置数据结构。
回答by SACn
Define a virtual index Z = (X+Y) now perform quick sort on Z and based on index Z pick elements (X, Y). Points on circle will lead to same Z (and obviously will stick together in sort results)
定义虚拟索引 Z = (X+Y) 现在对 Z 执行快速排序并基于索引 Z 选择元素 (X, Y)。圆上的点将导致相同的 Z(显然会在排序结果中粘在一起)