Iterating over several lists at once

Michael Spencer mahs at telcopartners.com
Wed Dec 13 18:50:00 EST 2006


John Henry wrote:
> Carl Banks wrote:
> <snip>
>> The function can be extended to allow arbitrary arguments.  Here's a
>> non-minmal recursive version.
>>
>> def cartesian_product(*args):
>>     if len(args) > 1:
>>         for item in args[0]:
>>             for rest in cartesian_product(*args[1:]):
>>                 yield (item,) + rest
>>     elif len(args) == 1:
>>         for item in args[0]:
>>             yield (item,)
>>     else:
>>         yield ()
>>
>>
> 
> Very nice.
> 
another implementation of cartesian_product using 'reduce' to add 
mystery ;-)

def star(outer, inner):
     for rest in outer:
         for item in inner:
             yield rest + (item,)

def cartesian_product(*args):
     return reduce(star, args, ((),))

  >>> list(cartesian_product("01","01","01"))
  [('0', '0', '0'), ('0', '0', '1'), ('0', '1', '0'), ('0', '1', '1'), 
('1', '0', '0'), ('1', '0', '1'), ('1', '1', '0'), ('1', '1', '1')]
  >>>

Michael




More information about the Python-list mailing list