我需要所有可能的长度为k的组合。
假设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>2
[(0, 0), (0, 1), (1, 0), (1, 1)]
答案 0 :(得分:15)
itertools.product()
采用repeat
关键字参数;将其设置为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)]