繁体   English   中英

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

[英]Generating all possibly length n combinations of two items in python

我试图从两个可能的项目生成长度为n的列表。 例如,一个示例可能是长度为4的列表,包括零或一个将为0000、0001、0010、0100、1000、1001等的数字。在此先感谢Jack

随着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 : itertools

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)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM