【发布时间】:2017-10-27 02:04:48
【问题描述】:
给定一个点列表,我想创建一个带有坐标的 numpy 数组。相关问题是here 和here。有谁知道这样做的正确或更有效的方法?
import numpy as np
# Please note that we have no control over the point class.
# This code just to generate the example.
class Point:
x = 0.0
y = 0.0
points = list()
for i in range(10):
p = Point()
p.x = 10.0
p.y = 5.0
points.append(p)
# The question starts here.
# The best I could come up with so far:
x = np.fromiter((p.x for p in points), float)
y = np.fromiter((p.y for p in points), float)
arr = np.vstack((x,y)).transpose()
【问题讨论】:
-
首先
x和y是Point的静态属性。您想要的是在Point中定义一个__init__(self, x, y)函数并执行self.x = x; self.y = y,这使得x和y属于aPoint,而不是Point类. -
这只是设置示例。我得到了一个具有适当 x 和 y 属性的对象列表,问题是如何从 python 列表中获取一个 numpy 数组。
-
好的。您可以将最后三行替换为:
arr = np.vstack(zip((p.x for p in points), (p.y for p in points))) -
老实说,您可以像这样设置整个事情:tio.run/##bY/BagMxDETP8VfoaIMxG0Ivhf5D7yUYk3gT011ZWE5Yf/…
-
谢谢。你真是太好了。我应该在问题中澄清我无法控制 Point 类。