Skip to main content
 首页 » 编程设计

python之将 numpy 数组 block 转换为元组

2025年01月19日10mq0036

我有一个像这样的 numpy 数组

array([[243], 
       [243], 
       [243], 
       [243], 
       [243], 
       [243], 
       [243], 
       [245], 
       [244], 
       [244], 
       [244], 
       [243], 

并且其中的每三个元素将被转换为一个元组!我写了一个像这样的简单生成器,

def RGBchunks(a_list): 
    for i in range(0,len(a_list),3): 
        temp = [] 
        for j in range(3): 
            temp.extend(a_list[i+j]) 
        yield tuple(temp) 

它给出了我想要的,像这样,

>>> for i in RGBchunks(my_arr): 
         print(i) 
 
 
(243, 243, 243) 
(243, 243, 243) 
(243, 243, 243) 
(244, 244, 244) 
(245, 245, 245) 
(244, ........ 
.............. 
(243, 243, 243) 

我很好奇在 numpy 中是否有一些简单优雅的方法来做到这一点!可能所有这些元组都在一个新列表中?我很好奇任何 Pythonic 方式。性能提升也会很好!

请您参考如下方法:

如果是没有任何重叠的简单整形操作,使用reshape:

my_arr.reshape(-1, 3) 

或者,

np.reshape(my_arr, (-1, 3)) 

array([[243, 243, 243], 
       [243, 243, 243], 
       [243, 245, 244], 
       [244, 244, 243]]) 

如果您真的想要一个元组列表,请在 reshape 后的结果上调用 map:

list(map(tuple, my_arr.reshape(-1, 3))) 

或者,通过对性能的列表理解:

[tuple(x) for x in my_arr.reshape(-1, 3)] 

[(243, 243, 243), (243, 243, 243), (243, 245, 244), (244, 244, 243)] 

对于重叠步幅,有stride_tricks:

f = np.lib.stride_tricks.as_strided 
n = 3 
 
f(my_arr, shape=(my_arr.shape[0] - (n + 1), n), strides=my_arr.strides) 
 
array([[243, 243, 243], 
       [243, 243, 243], 
       [243, 243, 243], 
       [243, 243, 243], 
       [243, 243, 243], 
       [243, 243, 245], 
       [243, 245, 244], 
       [245, 244, 244], 
       [244, 244, 244], 
       [244, 244, 243]])