Python 数组中 1 和 0 的组合

use*_*253 3 python combinations python-itertools python-2.7

我想在二维数组中组合 1 和 0,如下所示:

[[ 1, 1, 1, 1, 0, 0, 0, 0 ],
 [ 1, 1, 1, 0, 1, 0, 0, 0 ],
 [ 1, 1, 1, 0, 0, 1, 0, 0 ],
 [ 1, 1, 1, 0, 0, 0, 1, 0 ],
 [ 1, 1, 1, 0, 0, 0, 0, 1 ],
 .
 .
 .
]
Run Code Online (Sandbox Code Playgroud)

这意味着四个 1 和四个 0 的组合。我查看了itertools模块的permutations()and combinations(),但找不到任何合适的函数来执行这种组合。

usu*_* me 7

您还可以使用combinations直接生成独特的组合:

n = 8
n1 = 4
for x in itertools.combinations( xrange(n), n1 ) :
    print [ 1 if i in x else 0 for i in xrange(n) ] 

[1, 1, 1, 1, 0, 0, 0, 0]
[1, 1, 1, 0, 1, 0, 0, 0]
[1, 1, 1, 0, 0, 1, 0, 0]
[1, 1, 1, 0, 0, 0, 1, 0]
...
[0, 0, 0, 1, 1, 1, 0, 1]
[0, 0, 0, 1, 1, 0, 1, 1]
[0, 0, 0, 1, 0, 1, 1, 1]
[0, 0, 0, 0, 1, 1, 1, 1]
Run Code Online (Sandbox Code Playgroud)

这比permutations因为您不迭代不需要的解决方案更有效。

直觉是你试图找到所有可能的方法来适应长度为 8 的序列中的四个“1”;这就是组合的确切定义。那个数字是C(8,4)=8! / (4! * 4!) = 70。相反,使用的解决方案permutations迭代8! = 40,320候选解决方案。