Some thougts on cartesian products

Christoph Zwerschke cito at online.de
Sun Jan 22 21:11:37 CET 2006


Steven D'Aprano wrote:
> If you are happy to always return a list of tuples regardless of what the
> two operands are, generators make it so easy it is shameful. Even if you
> want a special case of two string arguments returning a string, it is
> hardly any more difficult:
> 
> def cartprod(A, B):
>     if type(A) == type(B) == str:
>         convert = lambda obj: "".join(list(obj))
>     else:
>         convert = lambda obj: obj  # do nothing
>     for a in A:
>         for b in B:
>             yield convert((a, b))

I didn't deny that it's handy; my "imul" example was pretty much the 
same. If you don't want to use the a*b syntax, it's a good solution.

-- Christoph



More information about the Python-list mailing list