简体   繁体   中英

Generating and merging all combinations of multiple lists python

Similiar questions to this one have been asked before, but none exactly like it an and I'm kind of lost.

If I have 2 sets of lists (or a lists of lists)

listOLists = [[1,2,3],[1,3,2]]
listOLists2 = [[4,5,6],[4,6,5]]

And I want 'merge' the two lists to make

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

How would I do this?

You may use generator to simplify your code, like this:

a = [[1, 2, 3], [1, 3, 2], [2, 1, 3]]
b = [[4, 5, 6], [4, 6, 5], [5, 4, 6]]
c = [i + j for i in a for j in b]
print c

Output:

[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 6, 5], [1, 2, 3, 5, 4, 6], [1, 3, 2, 4, 5, 6], [1, 3, 2, 4, 6, 5], [1, 3, 2, 5, 4, 6], [2, 1, 3, 4, 5, 6], [2, 1, 3, 4, 6, 5], [2, 1, 3, 5, 4, 6]]
list1s=[[1,2,3],[3,2,1],[2,2,2]]
list2s=[[3,3,3],[4,4,4],[5,5,5]]


for indis1 in list1s:
    for indis2 in list2s:
        print(indis1 + indis2)

try and;

[1, 2, 3, 3, 3, 3]
[1, 2, 3, 4, 4, 4]
[1, 2, 3, 5, 5, 5]
[3, 2, 1, 3, 3, 3]
[3, 2, 1, 4, 4, 4]
[3, 2, 1, 5, 5, 5]
[2, 2, 2, 3, 3, 3]
[2, 2, 2, 4, 4, 4]
[2, 2, 2, 5, 5, 5]
list1 = [[1,2,3],[1,3,2]]
list2 = [[4,5,6],[4,6,5]]

mergedLists = []

for list1_inner in list1:
  for list2_inner in list2:
    mergedLists.append(list1_inner + list2_inner)

print(mergedLists) 

A comparison of methods:

import itertools
import random
l1 = [[random.randint(1,100) for _ in range(100)]for _ in range(100)]
l2 = [[random.randint(1,100) for _ in range(100)]for _ in range(100)]

With itertools :

def itert(l1, l2):
    [list(itertools.chain(*x)) for x in itertools.product(l1, l2)]

With for loops:

def forloops(list1, list2):
    mergedLists = []
    for list1_inner in list1:
      for list2_inner in list2:
        mergedLists.append(list1_inner + list2_inner)

With a simple Comprehension:

def comp(l1, l2):
    [i + j for i in l1 for j in l2]

Speed

%time itert(l1, l2)
Wall time: 99.8 ms

%time comp(l1, l2)
Wall time: 31.3 ms

%time forloops(l1, l2)
Wall time: 46.9 ms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM