All possible replacements of two lists?

后端 未结 3 1309
长发绾君心
长发绾君心 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:25

    Creating 3 lists of two elements would not over-complicate the code at all. zip can "flip the axes" of multiple lists trivially (making X sequences of Y elements into Y sequences of X elements), making it easy to use itertools.product:

    import itertools
    
    a = [1,2,3]
    b = [4,5,6]
    
    # Unpacking result of zip(a, b) means you automatically pass
    # (1, 4), (2, 5), (3, 6)
    # as the arguments to itertools.product
    output = list(itertools.product(*zip(a, b)))
    
    print(*output, sep="\n")
    

    Which outputs:

    (1, 2, 3)
    (1, 2, 6)
    (1, 5, 3)
    (1, 5, 6)
    (4, 2, 3)
    (4, 2, 6)
    (4, 5, 3)
    (4, 5, 6)
    

    Different ordering than your example output, but it's the same set of possible replacements.

提交回复
热议问题