Skip to main content
 首页 » 编程设计

python之如何将包含嵌套数组的压缩对象展平到列表中

2025年05月04日26EasonJim

我有一个像这样的压缩对象:

z = zip(a, b) 
lst = list(z) 
 
print(lst) 

输出:

[(0, array([[72, 65], 
           [70, 71]], dtype=uint8)),  
(1, array([[ 71,  99], 
           [190, 163]], dtype=uint8)),  
(2, array([[52, 59], 
           [69, 72]], dtype=uint8)), etc... 

我想将此列表展平为以下内容:

[0, 72, 65, 70, 71, 1, 71, 99, 190, 163, 2, 52, 59 etc..] 

我试过用

y = sum(w, ()) 
# or  
y = list(itertools.chain(*lst)) 

但是当我打印时数组仍然存在。

我做错了什么?

请您参考如下方法:

使用其中之一

这是一个 MWE。

import numpy as np 
 
lists = [(0, np.array([ [72,  65], 
                        [70,  71]], dtype=np.uint8)),  
        (1, np.array([  [71,  99], 
                        [190, 163]], dtype=np.uint8))] 
 
l = list() 
for idx, array in lists: 
    l.append(idx) 
    l.extend(np.ravel(array))   # returns a contiguous flattened array 
    #l.extend(array.flat)       # return a 1-D iterator over the array. 
    #l.extend(array.flatten())  # return a copy of the array collapsed into one dimension  
 
print(l) 
# Output 
[0, 72, 65, 70, 71, 1, 71, 99, 190, 163] 

关于ravel和flatten的区别,摘自What is the difference between flatten and ravel functions in numpy? ,

The difference is that flatten always returns a copy and ravel returns a view of the original array whenever possible. This isn't visible in the printed output, but if you modify the array returned by ravel, it may modify the entries in the original array. If you modify the entries in an array returned from flatten this will never happen. ravel will often be faster since no memory is copied, but you have to be more careful about modifying the array it returns.