生成并合并多个列表python的所有组合

时间:2017-02-18 23:13:39

标签: python list permutation

以前曾经问过这个类似的问题,但没有一个完全喜欢它,而且我有点迷失。

如果我有2套清单(或清单清单)

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

我想要'合并'要制作的两个清单

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]]

我该怎么做?

4 个答案:

答案 0 :(得分:1)

您可以使用生成器来简化代码,如下所示:

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

输出:

[[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]]

答案 1 :(得分:1)

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)

尝试;

[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]

答案 2 :(得分:0)

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) 

答案 3 :(得分:0)

方法比较:

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)]

使用itertools

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

使用for循环:

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

简单的理解:

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

速度

%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