如何将numpy ndarray有效地转换为元组列表?

时间:2019-03-25 11:33:07

标签: python numpy

这是我得到的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()方法对我不起作用。

2 个答案:

答案 0 :(得分:3)

# 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))))
...

答案 1 :(得分:2)

您可以使用列表理解,它们比for循环要快

a = np.array([[[ 0.01, 0.02 ]], [[ 0.03, 0.04 ]]])
print([(i[0][0], i[0][1]) for i in a])  # [(0.01, 0.02), (0.03, 0.04)]

或者:

print([tuple(l[0]) for l in a])  # [(0.01, 0.02), (0.03, 0.04)]