on generating combinations among a variable list of lists

Boris Dorestand bdorestand at example.com
Sun Jun 28 12:59:01 EDT 2020


Peter Otten <__peter__ at web.de> writes:

> Boris Dorestand wrote:
>
>> Say we have [1,3,5,7], [2,3], [1,10].  I'd like to generate
>> 
>>   [1,2,1]
>>   [1,2,10]
>>   [1,3,1]
>>   [1,3,10]
>>   [3,2,1]
>>   [3,2,10]
>>   [3,3,1]
>>   [3,3,10]
>>   [5, ...]
>>   ...
>>   [7,3,10]
>> 
>> The number of input lists is variable.  The example shows three lists,
>> but there could be only one or ten lists or any other number of lists.
>> 
>> I looked at itertools.  There doesn't seem to be any procedure ready for
>> this.  I might have to combine some of them but I'm not yet sure how.
>
> itertools.product() seems to do what you want:
>
>>>> for t  in itertools.product([1,3,5,7], [2,3], [1,10]):
> ...    print(t)
> ... 
> (1, 2, 1)
> (1, 2, 10)
> (1, 3, 1)
> (1, 3, 10)
> (3, 2, 1)
> (3, 2, 10)
> (3, 3, 1)
> (3, 3, 10)
> (5, 2, 1)
> (5, 2, 10)
> (5, 3, 1)
> (5, 3, 10)
> (7, 2, 1)
> (7, 2, 10)
> (7, 3, 1)
> (7, 3, 10)

That's precisely it.  I missed product.  Thanks!

> If you need lists instead of tuples convert them
>
>>>> list(t)
> [7, 3, 10]
>
> To pass a varying number of lists use a list of lists and a star argument:
>
>>>> lists = [[[1, 2], [3, 4]], [[10, 20, 30], [40, 50]]]
>>>> for item in lists:
> ...     print(list(itertools.product(*item)))
> ... 
> [(1, 3), (1, 4), (2, 3), (2, 4)]
> [(10, 40), (10, 50), (20, 40), (20, 50), (30, 40), (30, 50)]

The star-syntax I didn't even know.  And it was very useful.  Thank you!


More information about the Python-list mailing list