小编典典

如何获取两个列表之间的所有映射?

python

我们有两个列表,A和B:

A = ['a','b','c']
B = [1, 2]

有没有一种pythonic的方法来构建A和B之间包含2 ^ n(此处为2 ^ 3 = 8)的所有映射的集合?那是:

[(a,1), (b,1), (c,1)]
[(a,1), (b,1), (c,2)]
[(a,1), (b,2), (c,1)]
[(a,1), (b,2), (c,2)]
[(a,2), (b,1), (c,1)]
[(a,2), (b,1), (c,2)]
[(a,2), (b,2), (c,1)]
[(a,2), (b,2), (c,2)]

使用itertools.product,可以获取所有元组:

import itertools as it
P = it.product(A, B)
[p for p in P]

这使:

Out[3]: [('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)]

阅读 225

收藏
2021-01-20

共1个答案

小编典典

您可以使用itertools.productzip

from itertools import product
print [zip(A, item) for item in product(B, repeat=len(A))]

输出量

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

product(B, repeat=len(A)) 产生

[(1, 1, 1),
 (1, 1, 2),
 (1, 2, 1),
 (1, 2, 2),
 (2, 1, 1),
 (2, 1, 2),
 (2, 2, 1),
 (2, 2, 2)]

然后,我们从产品中选择每个元素,并使用进行压缩A,以获得所需的输出。

2021-01-20