生成列表中所有可能的二进制值组合 Python

Generate all possible combinations of binary values in a list Python

我正在寻找一种方法来生成列表中所有可能的二进制组合。例如,如果我有 5 个可用空间,我想创建一个列表,其中包含 ["00000", ..., "11111"] 的所有可能组合,我不知道我是否已经解释清楚了,我在这里发现了一些类似的问题,但我在寻找时设法实现了它......

indexNames = ["00000", "00001", "00010", ..., "11111"]

如果 n = 5。

indexNames = ["00", "01", "10", "11"]

如果 n = 2。

你应该使用itertools.product

大致相当于生成器表达式中的嵌套 for 循环。例如,product(A, B)returns 与 ((x,y) for x in A for y in B)

相同

嵌套循环像里程表一样循环,每次迭代时最右边的元素都会前进。此模式创建字典顺序,因此如果输入的可迭代对象已排序,则产品元组将按排序顺序发出。

from itertools import product  

def get_binary(length):
    perm=product(['0', '1'], repeat=length)
    possible_bin=[]
    for i in list(perm):  
        my_bin=''.join(i) 
        possible_bin.append(my_bin)
    return possible_bin
  
print(get_binary(3))
print(get_binary(4))
print(get_binary(5))
['000', '001', '010', '011', '100', '101', '110', '111']
['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']
['00000', '00001', '00010', '00011', '00100', '00101', '00110', '00111', '01000', '01001', '01010', '01011', '01100', '01101', '01110', '01111', '10000', '10001', '10010', '10011', '10100', '10101', '10110', '10111', '11000', '11001', '11010', '11011', '11100', '11101', '11110', '11111']