首页 > 解决方案 > 在列表 Python 中生成所有可能的二进制值组合

问题描述

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

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

如果 n = 5。

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

如果 n = 2。

标签: pythonlistbinarycombinations

解决方案


您应该使用itertools.product

大致相当于生成器表达式中的嵌套 for 循环。例如, product(A, B) 返回与 ((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']

推荐阅读