获取长度为 3 [0,0,0] 到 [1,1,1] 的 [1,0] 的所有可能组合

Getting all possible combination for [1,0] with length 3 [0,0,0] to [1,1,1]

    from itertools import combinations
   
     
def n_length_combo(arr, n):
     
    # using set to deal
    # with duplicates 
    return list(combinations(arr, n))
   
# Driver Function
if __name__ == "__main__":
    arr = '01'
    n = 3
    print (n_length_combo([x for x in arr], n) )

预期输出

想要 0 和 1 的 3 种组合。尝试使用上面的示例,但它不起作用

您正在寻找 Cartesian product, not a combination or permutation of [0, 1]. For that, you can use itertools.product

from itertools import product

items = [0, 1]

for item in product(items, repeat=3):
    print(item)

这会生成您正在寻找的输出(尽管顺序略有不同):

(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)