[英]How can I enumerate all the possible N-long combinations of zeros and ones in Python?
I'd like to enumerate all the possible N-long lists of zeros and ones : [0,1,0,0,0,1,0,...]. 我想列举所有可能的N-long零列表:[0,1,0,0,0,1,0,...]。 So, basically an 2^N-long matrix of N-long elements.
所以,基本上是一个2 ^ N长的N长元素矩阵。 If N=3, I would do the following:
如果N = 3,我会做以下事情:
M = []
for i in range(2):
for j in range(2):
for k in range(2):
M.append([i,j,k])
I need a simpler way to do that for an arbitrary N (N<20). 对于任意N(N <20),我需要一种更简单的方法。 Thanks.
谢谢。
If you're a fan of itertools (and really, who isn't?), you can use itertools.product
to take a repeated Cartesian product of the binary digits [0, 1]
. 如果你是itertools的粉丝(真的,谁不是?),你可以使用
itertools.product
来获取二进制数字[0, 1]
的重复笛卡尔积。 Set the repeat
argument set to whatever length you want. 将
repeat
参数设置为您想要的任何长度。
>>> import itertools
>>> length = 3
>>> for thing in itertools.product([0, 1], repeat=length): print(thing)
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)
As a general rule of thumb, if you find yourself nesting a lot of similar-looking loops, there's probably a better way of solving your problem that involves using itertools. 作为一般的经验法则,如果您发现自己嵌套了许多类似外观的循环,那么可能有更好的方法来解决使用itertools的问题。
def binstr(n):
if n == 0:
return [""]
else:
rec = binstr(n-1)
return ["0"+x for x in rec] + ["1"+x for x in rec]
You can do that as follows 你可以这样做
M = []
for i in range ( 1<< N ):
tmp = i
bit_string=[]
for j in range(N):
bit_string.append(tmp%2)
tmp = tmp/2
M.append(bit_string)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.