我们有两个列表,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,可以获取所有元组:
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)]
您可以使用itertools.product和zip
zip
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)) 产生
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,以获得所需的输出。
A