Skip to main content
 首页 » 编程设计

python之在二维数组中进行所有可能的组合

2025年02月15日11jackei

我正在尝试制作一个包含所有可能组合的 4x4 (16) 像素黑白图像阵列。我制作了以下数组作为模板:

template = [[0,0,0,0],    # start with all white pixels 
            [0,0,0,0],     
            [0,0,0,0], 
            [0,0,0,0]] 

然后我想遍历模板并将每个可能的组合的 0 更改为 1。 我尝试用 numpy 和 itertools 进行迭代,但只能得到 256 种组合,根据我的计算,应该有 32000(编辑:65536!不知道那里发生了什么......)。有没有哪位高手可以帮助我?

请您参考如下方法:

正如您所说,您可以使用 itertools 模块来执行此操作,尤其是 product 函数:

import itertools 
import numpy as np 
 
# generate all the combinations as string tuples of length 16 
seq = itertools.product("01", repeat=16) 
 
for s in seq: 
    # convert to numpy array and reshape to 4x4 
    arr = np.fromiter(s, np.int8).reshape(4, 4) 
    # do something with arr