-2

I am trying to find all combinations to select exactly one element from each list inside a list. (I prefer the computationally fastest method.)

Example: If my list is [[1], [2,3], [4,5,6]] I would want to get the following result (in any order): [[1,2,4], [1,2,5], [1,2,6], [1,3,4], [1,3,5], [1,3,6]]

I tried finding functions in modules like itertools without any success and am not sure how to start this.

I was thinking about doing the following, but I have no idea how to finish this: Find the number of permutations to find (called m here):

m = 1
for letter in letters:
    m *= len(letter)

Then set up a for loop:

for i in range(m):

Then find each combination by cycling through all lists in the list and taking one element. I was thinking of doing the selection somehow using the modulus (%) function, but I don't know how to make it work.

petezurich
  • 9,280
  • 9
  • 43
  • 57
Ron Lauterbach
  • 107
  • 1
  • 1
  • 12
  • "I tried finding functions in modules like itertools" the answer is itertools product. Having said that, your approach to a solution is so weird, because you're trying to use indexes to iterate. Think of more pythonic loops, and this is much easier to tackle. – Paritosh Singh May 26 '19 at 09:38
  • @AndrewAllen That helps to find a random element, but what do I do to find every element? – Ron Lauterbach May 26 '19 at 09:41

1 Answers1

2

Sounds like you want itertools.product():

>>> for x in itertools.product([1], [2,3], [4,5,6]):
...   print(x)
...
(1, 2, 4)
(1, 2, 5)
(1, 2, 6)
(1, 3, 4)
(1, 3, 5)
(1, 3, 6)
AKX
  • 152,115
  • 15
  • 115
  • 172