Combining arbitrary lists
Steve Holden
steve at holdenweb.com
Mon Nov 15 08:19:17 EST 2004
Thorsten Kampe wrote:
> * Nick (2004-11-15 04:28 +0100)
>
>>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]
>>
>>--output--
>>[1, 4, 7]
>>[1, 4, 8]
>>[1, 5, 7]
>>[1, 5, 8]
>> ...
>>[3, 6, 8]
>>-- --
>>
>>How can I do this for an arbirary length of n?
>
>
> This is the Cartesian product of three sets. Have a look at
> http://www.thorstenkampe.de/python/utils.py:
>
> def cartes(seq0, seq1, modus = 'pair'):
> """ return the Cartesian Product of two sequences """
> if modus == 'pair':
> return [[item0, item1] for item0 in seq0 for item1 in seq1]
> elif modus == 'triple':
> return [item0 + [item1] for item0 in seq0 for item1 in seq1]
>
> Then you would generate your output like this:
>
>>>>cartes(cartes([1, 2, 3], [4, 5, 6]), [7, 8], 'triple')
I think the point of the question was to act on an arbitrary number of
length-3 lists.
regards
Steve
--
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119
More information about the Python-list
mailing list