Python merging two lists with all possible permutations

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

    Try this:

    combos=[]
    for i in list1:
          for j in list2:
              combos.append([i,j])
    print combos
    
    0 讨论(0)
  • 2020-12-02 15:23

    The accepted answer can be simplified to

    a = [1, 2, 3]
    b = [4, 5, 6]
    [list(zip(a, p)) for p in permutations(b)]
    

    (The list() call can be omitted in Python 2)

    0 讨论(0)
  • 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]]
    
    0 讨论(0)
  • 2020-12-02 15:23

    As @pacholik s answer does not cover lists of different length, here is my solution, using a list comprehension with two variables:

    first_list = [1, 2, 3]
    second_list = ['a', 'b']
    
    combinations = [(a,b) for a in first_list for b in second_list]
    

    The output looks like this:

    [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
    
    0 讨论(0)
  • 2020-12-02 15:28

    You can create a list by constructing all the permutations of two list members with this, containing the list combinations.

    lst1 = [1,2]
    lst2 = [3,4]
    
    #lst = [[j,k] for j in lst1 for k in lst2] # [[1,3],[1,4],[2,3],[2,4]]
    lst = [[[j,k] for j in lst1] for k in lst2] # [[[1,3],[2,3]],[[1,4],[2,4]]]
    print lst
    
    0 讨论(0)
  • 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)]
    
    0 讨论(0)
提交回复
热议问题