All possible replacements of two lists?

后端 未结 3 1313
长发绾君心
长发绾君心 2020-12-11 20:53

(I am aware that the title of the question might be misleading, but I could not find any other way to formulate it - feel free to edit it)

I have two lists, both of

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-11 21:27

    Okay this is similar to the other answers, but taking a bit from both. You can model your problem as finding all possible bits of a sequence of given length, and replacing only when there is 1, and otherwise not.

    from itertools import product
    
    a = [1,2,3]
    b = [4,5,6]
    
    ## All binary combinations of length of a (or b)
    combinations = product([0,1], repeat=len(a))
    
    for combination in combinations:
        y = []
        for l, i in zip(zip(a,b),combination):
             y.append(l[i])
        print y
    

    All combinations of bits are:

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

    Which results in:

    [1, 2, 3]
    [1, 2, 6]
    [1, 5, 3]
    [1, 5, 6]
    [4, 2, 3]
    [4, 2, 6]
    [4, 5, 3]
    [4, 5, 6]
    

提交回复
热议问题