【发布时间】:2014-04-14 10:42:25
【问题描述】:
我们有两个列表,A 和 B:
A = ['a','b','c']
B = [1, 2]
有没有一种 Python 的方法来构建 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)]
【问题讨论】:
标签: python list combinatorics itertools