进行2D阵列中的所有可能组合 [英] Make every possible combination in 2D array

查看:58
本文介绍了进行2D阵列中的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作具有所有可能组合的4x4(16)像素黑白图像阵列.我将以下数组作为模板:

I'm trying to make an array of 4x4 (16) pixel black and white images with all possible combinations. I made the following array as a template:

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!不知道那里发生了什么……).任何具有疯狂技巧的人都可以帮助我吗?

I then want to iterate through the template and changing the 0 to 1 for every possible combination. I tried to iterate with numpy and itertools but can only get 256 combinations, and with my calculations there should be 32000 ( 65536! don't know what happened there...). Any one with mad skills that could help me out?

推荐答案

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

As you said, you can use the itertools module to do this, in particular the product function:

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

这篇关于进行2D阵列中的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆