在Python中,平均表示多个多边形的点数组的最佳方法是什么?
我目前的代码是:
poly1 = [(2, 2), (10, 0), (10, 10), (2, 10)]
poly2 = [(4, 4), (20, 0), (20, 20), (4, 20)]
polys = []
polys.append(poly1)
polys.append(poly2)
x1 = []
x2 = []
x3 = []
x4 = []
y1 = []
y2 = []
y3 = []
y4 = []
for poly in polys:
x1.append(poly[0][0])
y1.append(poly[0][1])
x2.append(poly[1][0])
y2.append(poly[1][1])
x3.append(poly[2][0])
y3.append(poly[2][1])
x4.append(poly[3][0])
y4.append(poly[3][1])
avg_x1 = np.average(np.array(x1))
avg_y1 = np.average(np.array(y1))
avg_x2 = np.average(np.array(x2))
avg_y2 = np.average(np.array(y2))
avg_x3 = np.average(np.array(x3))
avg_y3 = np.average(np.array(y3))
avg_x4 = np.average(np.array(x4))
avg_y4 = np.average(np.array(y4))
new_poly = [(avg_x1, avg_y1),(avg_x2, avg_y2),(avg_x3, avg_y3),(avg_x4, avg_y4)]
print(new_poly)
这给出了正确答案,
[(3.0, 3.0), (15.0, 0.0), (15.0, 15.0), (3.0, 15.0)]
但必须有一种更有效的方法。
答案 0 :(得分:0)
使用numpy:使用numpy的矢量化Properties
并使用map来转换回元组列表:
mean
没有numpy:使用嵌套列表理解/生成器表达式:
>>> list(map(tuple, np.mean(polys, axis=0)))
[(3.0, 3.0), (15.0, 0.0), (15.0, 15.0), (3.0, 15.0)]
答案 1 :(得分:0)
使用numpy的简单而优雅的方式
data = np.array([poly1, poly2])
[tuple(l) for l in np.average(data, axis=0)]
输出:
[(3.0, 3.0), (15.0, 0.0), (15.0, 15.0), (3.0, 15.0)]