Python merging two lists with all possible permutations

后端 未结 7 1790
醉话见心
醉话见心 2020-12-02 15:09

I\'m trying to figure out the best way to merge two lists into all possible combinations. So, if I start with two lists like this:

list1 = [1, 2]
list2 = [3,         


        
7条回答
  •  情歌与酒
    2020-12-02 15:30

    repeat the first list, permutate the second and zip it all together

    >>> from itertools import permutations, repeat
    >>> a = [1, 2, 3]
    >>> b = [4, 5, 6]
    >>> list(list(zip(r, p)) for (r, p) in zip(repeat(a), permutations(b)))
    [[(1, 4), (2, 5), (3, 6)],
     [(1, 4), (2, 6), (3, 5)],
     [(1, 5), (2, 4), (3, 6)],
     [(1, 5), (2, 6), (3, 4)],
     [(1, 6), (2, 4), (3, 5)],
     [(1, 6), (2, 5), (3, 4)]]
    

    EDIT: As Peter Otten noted, the inner zip and the repeat are superfluous.

    [list(zip(a, p)) for p in permutations(b)]
    

提交回复
热议问题