How to use itertools on a double list?

45 Views Asked by At

Say I have a list and I can only pick from 1 option from each sublist. How can I use itertools combination to form all possible choices such as the example below

A = [[1, 5],[2, 6], [3, 7], [4, 8]]

#need a return of a data set of [[1,2,3,4], [1,2,3,8],[1,2,7,4], [1,2,7,8], [1,6,3,4], [1,6,3,8]...]

Should outcome 16 choices to choose from but I can't seem to get combination function to work

for v in itertools.combinations(A, 3):
    print(v)

which returns

([1, 5], [2, 6], [3, 7])
([1, 5], [2, 6], [4, 8])
([1, 5], [3, 7], [4, 8])
([2, 6], [3, 7], [4, 8])
1

There are 1 best solutions below

1
Barmar On

Use itertools.product() to get a cross product of all the lists. Use the spread operator to turn each nested list into an argument to the function.

for v in itertools.product(*A):
    print(v)

outputs:

(1, 2, 3, 4)
(1, 2, 3, 8)
(1, 2, 7, 4)
(1, 2, 7, 8)
(1, 6, 3, 4)
(1, 6, 3, 8)
(1, 6, 7, 4)
(1, 6, 7, 8)
(5, 2, 3, 4)
(5, 2, 3, 8)
(5, 2, 7, 4)
(5, 2, 7, 8)
(5, 6, 3, 4)
(5, 6, 3, 8)
(5, 6, 7, 4)
(5, 6, 7, 8)