簡體   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