我有多个数组如下
A[0] = [a1, a2, a3]
A[1] = [b1, b2]
...
A[k-1] = [k1, ...]
我想生成所有可能的向量[a?, b?, ..., k?]
我查看了itertool库,但它并不符合我的需要。
我怎样才能做到这一点。 (我虽然关于递归,但我想有一个更简单的解决方案)。
答案 0 :(得分:4)
from itertools import product
for vector in product(*A):
# vector is [a[0], b[0], ..., k[0]] through to [a[k-1], [b[k-1], ..., k[k-1]]
# odometer style
演示:
>>> from itertools import product
>>> A = [[1, 2, 3], ['foo', 'bar'], ['spam', 'eggs']]
>>> for vector in product(*A):
... print vector
...
(1, 'foo', 'spam')
(1, 'foo', 'eggs')
(1, 'bar', 'spam')
(1, 'bar', 'eggs')
(2, 'foo', 'spam')
(2, 'foo', 'eggs')
(2, 'bar', 'spam')
(2, 'bar', 'eggs')
(3, 'foo', 'spam')
(3, 'foo', 'eggs')
(3, 'bar', 'spam')
(3, 'bar', 'eggs')