生成 python 中两项的所有可能长度 n 的组合

Generating all possibly length n combinations of two items in python

我正在尝试从两个可能的项目中生成一个长度为 n 的列表。例如一个例子可能是,一个长度为 4 的列表,其中包含 0 或 1,它们可能是 0000、0001、0010、0100、1000、1001 等。 提前致谢, 杰克

itertools.product:

In [1]: from itertools import product

In [2]: list(product((0, 1), repeat=4))
Out[2]: 
[(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)]

您也可以将整数打印为二进制字符串:

In [3]: for i in range(2**4):
   ...:     print('{:04b}'.format(i))
   ...:     
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

检查 itertools 模块中的 product 函数:https://docs.python.org/2/library/itertools.html#itertools.product

from itertools import product

product(range(2), repeat=4)
# --> <itertools.product object at 0x10bdc1500>

list(product(range(2), repeat=4))
# --> [(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)]