Simple cartesian product
Neel Krishnaswami
neelk at brick.cswv.com
Tue Jan 4 19:56:11 EST 2000
Magnus L. Hetland <mlh at vier.idi.ntnu.no> wrote:
>
> [Cartesian product using list operators]
>
> >>> def product(a,b):
> ... a2 = reduce(lambda l, x, n=len(b): l + [x]*n,
> ... [[]] + a)
> ... b = b * len(a)
> ... return map(None, a2, b)
Here's my entry:
def product(a, b):
u = map(lambda i: a[i/len(a)], range(len(a)*len(b)))
v = map(lambda j: b[j%len(b)], range(len(a)*len(b))) # Same as b*len(a)
return map(None, u, v)
>>> product([1,2,3], ['a','b'])
[(1, 'x'), (1, 'y'), (1, 'x'), (2, 'y'), (2, 'x'), (2, 'y')]
Obviously, if you want to save your sanity the nested for-loops are
the way to go. :)
Neel
More information about the Python-list
mailing list