简体   繁体   English

如何在Python中枚举所有可能的零和0的N长组合?

[英]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.

相关问题 生成零和b的所有可能组合 - Generating all possible combinations of a zeros and b ones 如何从 n 个列表中形成所有可能的组合 - How can I form all possible combinations from n lists 如何计算 Python 中 N 个不同词典的所有组合 - How can I calculate all combinations of N different dictionaries in Python 我如何获得所有n? 可以从数字 1 到 n 创建的可能列表的组合? - How do I get all n! combinations of possible lists that can be created from numbers 1 to n? 如何找到列表列表的所有可能组合(在Python中)? - How can I find all the possible combinations of a list of lists (in Python)? 枚举 Python 中标记球和标记箱问题中的所有可能组合 - Enumerate all possible combinations in labeled balls and labeled bins problem in Python 找到 m 长列表的所有 n 长排列(有重复),n>m - find all n-long permutations (with repeats) of m-long list, n>m 如何在Python中按零和一的向量排列顺序,使最后一个索引上带有零的向量保持在底部? - How can I arrange vectors of Zeros and Ones in Python, in an order on which the vectors with ones on the last index stay on the bottom? Python - 生成给定长度的1和0的所有可能数组的算法 - Python - Algorithm to generate all possible arrays of ones and zeros of a given length 如何删除所有 7 个字符长的零 python - how to remove all zeros that are 7 characters long python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM