python所有可能的0和1长度k的组合

时间:2022-11-24 21:23:40

I need all possible combinations of 0,1 of length k.

我需要所有可能的长度为k的组合。

Suppose k=2 I want (0,0), (0,1), (1,0), (1,1)

假设k=2 (0,0) (0,1) (1,0) (1,1)

I have tried different function in itertools but I did not find what I want.

我在itertools中尝试了不同的函数,但是没有找到我想要的。

>>> list(itertools.combinations_with_replacement([0,1], 2))
[(0, 0), (0, 1), (1, 1)]
>>> list(itertools.product([0,1], [0,1])) #does not work if k>2
[(0, 0), (0, 1), (1, 0), (1, 1)]

1 个解决方案

#1


15  

itertools.product() takes a repeat keyword argument; set it to k:

product()接受repeat关键字参数;将其设置为凯西:

product(range(2), repeat=k)

Demo:

演示:

>>> from itertools import product
>>> for k in range(2, 5):
...     print list(product(range(2), repeat=k))
... 
[(0, 0), (0, 1), (1, 0), (1, 1)]
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]

#1


15  

itertools.product() takes a repeat keyword argument; set it to k:

product()接受repeat关键字参数;将其设置为凯西:

product(range(2), repeat=k)

Demo:

演示:

>>> from itertools import product
>>> for k in range(2, 5):
...     print list(product(range(2), repeat=k))
... 
[(0, 0), (0, 1), (1, 0), (1, 1)]
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]