我正在尝试从两个可能的项目生成长度为n的列表。例如一个示例可以是,长度为4的列表,其包括0或1,其将是0000,0001,0010,0100,1000,1001等。 提前致谢, 千斤顶
答案 0 :(得分:8)
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
答案 1 :(得分:0)
查看product
模块中的itertools
功能: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)]