Skip to main content
 首页 » 编程设计

python之获取所有可能的长度为 n 的二进制元组的列表

2025年05月04日16zhwl

我需要一个返回长度为n的所有可能的二进制元组的列表的函数,如下所示:

binaryTuples(n=2) =>  [(0,0),(0,1),(1,0),(1,1)] 
binaryTuples(n=3) =>  [(0,0,0),(0,0,1),(0,1,1),(1,1,1) ... and so on] 

我知道这可以用 itertools 来完成,但我不知道怎么做。

请您参考如下方法:

尝试:

itertools.product(*[(0, 1)] * n) 

其中 n 是所需的大小。

例子:

import itertools 
print "For n = 2: " + str(list(itertools.product(*[(0, 1)] * 2))) 
print "For n = 3: " + str(list(itertools.product(*[(0, 1)] * 3))) 

输出:

For n = 2: [(0, 0), (0, 1), (1, 0), (1, 1)]                                                                                                                       
For n = 3: [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]   

您可以实时运行它 here .

我的灵感来自 generating binary numbers of size n as tuples : itertools.product(*[(0, 1)] * n) ,但没有标记为重复,因为它不是您想要的。 ;)