这是我得到的numpy.ndarray:a=[[[ 0.01, 0.02 ]], [[ 0.03, 0.04 ]]]
我想将其转换为a = [(0.01, 0.02), (0.03, 0.04)]
目前,我仅使用以下for
循环,但不确定其效率是否足够:
b = []
for point in a:
b.append((point[0][0], point[0][1]))
print(b)
我找到了a similar question,但是没有元组,因此建议的
ravel().tolist()
方法对我来说不起作用。 最佳答案
# initial declaration
>>> a = np.array([[[ 0.01, 0.02 ]], [[ 0.03, 0.04 ]]])
>>> a
array([[[0.01, 0.02]],
[[0.03, 0.04]]])
# check the shape
>>> a.shape
(2L, 1L, 2L)
# use resize() to change the shape (remove the 1L middle layer)
>>> a.resize((2, 2))
>>> a
array([[0.01, 0.02],
[0.03, 0.04]])
# faster than a list comprehension (for large arrays)
# because numpy's backend is written in C
# if you need a vanilla Python list of tuples:
>>> list(map(tuple, a))
[(0.01, 0.02), (0.03, 0.04)]
# alternative one-liner:
>>> list(map(tuple, a.reshape((2, 2))))
...
关于python - 如何有效地将numpy ndarray转换为元组列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55336870/