python长度为k的0,1的所有可能组合
我需要长度为k的0,1的所有可能组合 假设k=2,我想要python长度为k的0,1的所有可能组合,python,combinations,itertools,Python,Combinations,Itertools,我需要长度为k的0,1的所有可能组合 假设k=2,我想要(0,0)、(0,1)、(1,0)、(1,1) 我在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>
(0,0)、(0,1)、(1,0)、(1,1)
我在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)]
采用重复
关键字参数;将其设置为k
:
product(range(2), repeat=k)
演示:
我所说的快速是指计算上的快速:-)
>>> 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)]