Python合并具有所有可能排列的两个列表 [英] Python merging two lists with all possible permutations

查看:130
本文介绍了Python合并具有所有可能排列的两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出将两个列表合并为所有可能组合的最佳方法.因此,如果我从两个这样的列表开始:

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

结果列表如下:

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

也就是说,它基本上会生成一个列表列表,其中包括所有可能的组合.

That is, it basically produces a list of lists, with all the potential combinations between the two.

我一直在研究itertools,我肯定可以找到答案,但是我无法提出一种使它以这种方式起作用的方法.我最接近的是:

I've been working through itertools, which I'm pretty sure holds the answer, but I can't come up with a way to make it act this way. The closest I came was:

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

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

So it does all the possible combinations of items in each list, but not all the possible resulting lists. How do I get that to happen?

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

The end goal is to be able to individually process each list to determine efficiency (the actual data I'm working with is more complex). So, in the original example above, it would work something like this:

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循环并继续进行.其他形式的输出也可以使用,但似乎最简单.

If I got the "list of lists of lists" output I described above, then I could put it into a for loop and process on. Other forms of output would work, but it seems the simplest to work with.

推荐答案

repeat第一个列表,permutate第二个列表,zip全部列表

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

编辑:正如Peter Otten指出的那样,内部的ziprepeat是多余的.

EDIT: As Peter Otten noted, the inner zip and the repeat are superfluous.

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

这篇关于Python合并具有所有可能排列的两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆