C# 顺时针对列表中的二维点排序
基本上我有一个点列表,每个点都有X,Y,Z(Z总是一样的) 例如:C# 顺时针对列表中的二维点排序,c#,coordinates,C#,Coordinates,基本上我有一个点列表,每个点都有X,Y,Z(Z总是一样的) 例如: pointList.add(Point p = new Point(1, 2, 3)); 然而,我有麻烦排序成顺时针顺序他们 我知道中心,我知道每个列表中大约有600个点 我以前在Python中完成过这项工作,但在C#中遇到了麻烦 Python代码: pointlist.sort(key=lambda c:atan2(c[0], c[1])) 不确定这是否能满足您的需要 points = points.OrderBy(x =
pointList.add(Point p = new Point(1, 2, 3));
然而,我有麻烦排序成顺时针顺序他们
我知道中心,我知道每个列表中大约有600个点
我以前在Python中完成过这项工作,但在C#中遇到了麻烦
Python代码:
pointlist.sort(key=lambda c:atan2(c[0], c[1]))
不确定这是否能满足您的需要
points = points.OrderBy(x => Math.Atan2(x.X, x.Y)).ToList();
不是很优化或者什么的,只是看了看你的python代码,认为这也可以达到同样的效果
注意:您可能需要使用System.Linq
,除非您已经有了它
编辑:
Sturm指出,颠倒顺序可能是必要的,以便让他们“按时钟运行”
实现这一点的一种方法是使用
OrderByDescending
而不是OrderBy
为任何人提供排序方法(XX,YY)
不仅(0,0)
代码需要稍微修改
points.OrderBy(x=>Math.Atan2(x.x-XX,x.Y-YY)).ToList();
如果有人正在寻找一个完整的代码来对python中的中心点进行2D点排序
import numpy as np
import math
def carttopolar(x,y,x0=0,y0=0):
'''
cartisian to polar coordinate system with origin shift to x0,y0
'''
x1=x-x0
y1=y-y0
#print('(x0,y0)sort',x0,y0)
r = np.sqrt(x1**2+y1**2)
t = np.arctan2(y1,x1)*180/math.pi
if y1<0:
t=360+t
#print('x,y,r,t',x,y,r,t)
return r,t
def sort_aniclkwise(xy_list,x0=None,y0=None):
'''
Sort points anit clockwise with x0 y0 as origin
'''
if x0 is None and y0 is None:
(x0,y0)=np.mean(xy_list,axis=0).tolist()
elif x0 is None:
(x0,_)=np.mean(xy_list,axis=0).tolist()
elif y0 is None:
(_,y0)=np.mean(xy_list,axis=0).tolist()
print('origin used:',[x0,y0])
for i in range(len(xy_list)):
xy_list[i].append(i)
xy_list1 = sorted(xy_list, key=lambda a_entry: carttopolar(a_entry[0], a_entry[1],x0,y0)[1])
sort_index = []
for x in xy_list1:
sort_index.append(x[2])
del x[2]
return xy_list1, sort_index
if __name__ == '__main__':
#xy_list=[[1,1], [1,-1], [-1,1], [-1,-1]]
xy_list=[[1,2], [1,0], [-1,2], [-1,0]]
print ('xy_list',xy_list)
xy_list1,sort_index=sort_aniclkwise(xy_list)
print ('xy_list',xy_list)
print ('sort_index',sort_index)
'''
x,y = 1,0.00001
r,t=carttopolar(x,y,x0=0,y0=0)
print(r)
print(t)
a = ([[1,1], [1,-1], [-1,1], [-1,-1]])
print (a)
a = sorted(a, key=lambda a_entry: carttopolar(a_entry[0], a_entry[1]))
print (a)
'''
将numpy导入为np
输入数学
def carttopolar(x,y,x0=0,y0=0):
'''
从卡地西亚坐标系到极坐标系,原点移动到x0,y0
'''
x1=x-x0
y1=y-y0
#打印(‘(x0,y0)排序’,x0,y0)
r=np.sqrt(x1**2+y1**2)
t=np.arctan2(y1,x1)*180/数学π
如果您希望您的列表在默认情况下进行排序?如果是这样,可能最好使用自定义的IComparer
(或,)将点保存在一个排序的集合中。如果需要在“之后”遍历列表,请对其进行排序。更好的使用方法是foreach(points.OrderBy中的var point(x=>Math.Atan2(x.x,x.Y)))[do stuff with point]
,因为您是在“循环”时枚举它,而不是先枚举它,然后迭代。如果需要顺时针顺序,可能需要颠倒顺序。@Sturm“may”是什么意思?在某些情况下,您需要反转,而在其他情况下,您需要反转?你怎么知道?@t0yk4t在这种情况下不起作用