Python merging two lists with all possible permutations

后端 未结 7 1817
醉话见心
醉话见心 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:23

    Try to use list generator to create the nested lists:

    >>> [[[x,y] for x in list1] for y in list2]
    [[[1, 3], [2, 3]], [[1, 4], [2, 4]]]
    >>>
    

    Or, if you want one-line list, just delete brackets:

    >>> [[x,y] for x in list1 for y in list2]
    [[1, 3], [1, 4], [2, 3], [2, 4]]
    

提交回复
热议问题