Combining arbitrary lists

Bengt Richter bokr at oz.net
Mon Nov 15 04:36:54 EST 2004


On Mon, 15 Nov 2004 00:57:03 -0300, Mariano Draghi <mdraghi at prosud.com> wrote:

>Nick wrote:
>> Given that
>> 
>> n = [ [1, 2, 3], [4, 5, 6], [7, 8] ]
>> 
>> then the following code produces what I expect
>> 
>> for x in n[0]:
>>   for y in n[1]:
>>     for z in n[2]:
>>       print [x, y, z]
>
>...
>> 
>> How can I do this for an arbirary length of n?
>
>I think this is what you're looking for:
>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302478
>
Following is a slightly more compact generator (unless I goofed ;-)
(untested beyoud what you see here; probably traded a little speed for code lines)

 >>> n
 [[1, 2, 3], [4, 5, 6], [7, 8]]

 >>> def doit(LOL):
 ...     if not LOL: yield []; return
 ...     for h in LOL[0]:
 ...         for t in doit(LOL[1:]):
 ...             yield [h] + t
 ...
 >>> for row in doit(n): print row
 ...
 [1, 4, 7]
 [1, 4, 8]
 [1, 5, 7]
 [1, 5, 8]
 [1, 6, 7]
 [1, 6, 8]
 [2, 4, 7]
 [2, 4, 8]
 [2, 5, 7]
 [2, 5, 8]
 [2, 6, 7]
 [2, 6, 8]
 [3, 4, 7]
 [3, 4, 8]
 [3, 5, 7]
 [3, 5, 8]
 [3, 6, 7]
 [3, 6, 8]

 >>> for row in doit([[1,2],[3,4,5]]): print row
 ...
 [1, 3]
 [1, 4]
 [1, 5]
 [2, 3]
 [2, 4]
 [2, 5]


Regards,
Bengt Richter



More information about the Python-list mailing list