Python 如何得到n个二进制值的所有组合?

Python 如何得到n个二进制值的所有组合?,python,list,math,python-2.7,Python,List,Math,Python 2.7,在Python中,如何获得n二进制值0和1的所有组合 例如,如果n=3,我希望 [ [0,0,0], [0,0,1], [0,1,0], [0,1,1], ... [1,1,1] ] #total 2^3 combinations 我如何才能做到这一点?使用 这将产生一个元组列表(请参阅) 您可以轻松地将其更改为使用变量repeat: n = 3 lst = list(itertools.product([0, 1], repeat=n)) 如果您需要列表列表,则可以使用map功能(感谢@

在Python中,如何获得
n
二进制值
0
1
的所有组合

例如,如果
n=3
,我希望

[ [0,0,0], [0,0,1], [0,1,0], [0,1,1], ... [1,1,1] ]  #total 2^3 combinations
我如何才能做到这一点?

使用

这将产生一个元组列表(请参阅)

您可以轻松地将其更改为使用变量
repeat

n = 3
lst = list(itertools.product([0, 1], repeat=n))
如果您需要列表列表,则可以使用
map
功能(感谢@Aesthete)

或者在Python 3中:

lst = list(map(list, itertools.product([0, 1], repeat=n)))
# OR
lst = [list(i) for i in itertools.product([0, 1], repeat=n)]

请注意,使用
map
或列表理解意味着您不需要将产品转换为列表,因为它将遍历
itertools.product
对象并生成列表。

以下内容将为您提供所有此类组合

bin = [0,1]
[ (x,y,z) for x in bin for y in bin for z in bin ]

不使用任何内置函数或智能技术,我们可以得到这样的结果

def per(n):
    for i in range(1<<n):
        s=bin(i)[2:]
        s='0'*(n-len(s))+s
        print (map(int,list(s)))
per(3)       

他给出的
n=3
只是一个例子,所以他想将其参数化。这是可行的,但n不能太大……这不会扩展+1-
map(list,product([0,1],repeat=3))
将返回相同的格式,以防OP感兴趣。这很好,tuple也可以。@Volatility,出于好奇,你是怎么知道的?我不知道如何从Python文档中找到这个函数。@LWZ它。(见第6点)@Volatility,多好的帖子,谢谢@eumiro,我想我的问题也相当于这个,但那个答案给出的是一个字符串而不是一个列表。对我来说,这就产生了:必须调用(list(map…)才能得到实际的列表好主意!下面是一个带有格式函数的简单版本:``def per(n):用于范围(1>per(3)中的i
bin = [0,1]
[ (x,y,z) for x in bin for y in bin for z in bin ]
def per(n):
    for i in range(1<<n):
        s=bin(i)[2:]
        s='0'*(n-len(s))+s
        print (map(int,list(s)))
per(3)       
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]