繁体   English   中英

Python将两个列表与所有可能的排列合并

[英]Python merging two lists with all possible permutations

我试图找出将两个列表合并为所有可能组合的最佳方法。 所以,如果我从这样的两个列表开始:

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

结果列表如下所示:

[[[1,3], [2,4]], [[1,4], [2,3]]]

也就是说,它基本上产生一个列表列表,其中包含两者之间的所有潜在组合。

我一直在研究itertools,我很确定答案,但是我无法想出办法让它以这种方式行事。 我最接近的是:

list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
print list(itertools.product(list1, list2))

哪个产生:

[(1, 5), (1, 6), (1, 7), (1, 8), (2, 5), (2, 6), (2, 7), (2, 8), (3, 5), (3, 6), (3, 7), (3, 8), (4, 5), (4, 6), (4, 7), (4, 8)]

因此,它会在每个列表中执行所有可能的项目组合,但不是所有可能的结果列表。 我怎么做到这一点?

编辑:最终目标是能够单独处理每个列表以确定效率(我正在使用的实际数据更复杂)。 因此,在上面的原始示例中,它将工作如下:

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

Get first merged list: [[1,3], [2, 4]]
    Do stuff with this list
Get second merged list: [[1,4], [2, 3]]
    Do stuff with this list

如果我得到了上面描述的“列表列表”输出,那么我可以将它放入for循环并进行处理。 其他形式的输出可行,但似乎最简单的工作。

repeat第一个列表, permutate第二个列表并将它们zip在一起

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

编辑 :正如Peter Otten所说,内部ziprepeat是多余的。

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

接受的答案可以简化为

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

(Python中可以省略list()调用2)

尝试使用列表生成器来创建嵌套列表:

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

或者,如果您想要单行列表,只需删除括号:

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

编辑我的代码,为您提供所需的输出。

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

for a in list1:
    new_list = []
    for b in list2:
        new_list.append([a, b])
    combined.append(new_list)

print combined

您可以通过构造包含列表组合的两个列表成员的所有排列来创建列表。

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

由于@pacholik的答案不包括不同长度的列表,这里是我的解决方案,使用包含两个变量的列表解析:

first_list = [1, 2, 3]
second_list = ['a', 'b']

combinations = [(a,b) for a in first_list for b in second_list]

输出如下所示:

[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]

试试这个:

combos=[]
for i in list1:
      for j in list2:
          combos.append([i,j])
print combos

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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