combinations of variable length nested lists

David C. Ullrich ullrich at math.okstate.edu
Wed Aug 8 09:59:35 EDT 2001


On Tue, 07 Aug 2001 21:41:39 +0200, Just van Rossum
<just at letterror.com> wrote:

>I wrote:
>
>> This one uses list comprehensions (it's based on David Ullrich's version):
>> 
>>[ ..snipped recursive version.. ]
>
>It turns out a non-recursive version was easier than I thought (also using
>list comprehensions):
>
>
>input = [[1, 2], [4, 5, 6], [8, 11]]
>
>def permute(alist):
>    results = [[]]
>    for i in range(len(alist)):
>        results = [res + [item] for res in results for item in alist[i]]
>    return results

Huh.

I gotta get me a version with those list comprehensions (some day
when I feel like redoing a lot of xml stuff...). _Not_ that it
matters, just curious: Have you compared the performance of this
with other versions? Last time it came up list-comprehension
versions were surprisingly slow (istr).

(It _really_ doesn't matter, but I don't think that "permute"
is really the best name: "permute(alist)" sounds to me like
a list containing all the permutations of alist, so for
example permute(input) would be a list containing six items,
each of which is a list of three lists in different order.
Really does seem like what we're calculating here is the
cartesian product of the lists in alist.)

>all = permute(input)
>for x in all:
>    print x
>print
>
>
>Just


David C. Ullrich



More information about the Python-list mailing list