Skip to main content
 首页 » 编程设计

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

2025年05月04日19lvdongjie

这是我得到的 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)))) 
...