0

Total python rookie here. I wish to iterate through three lists, where the first two should be recombined in all possible ways while only one value is appended to each combination from third list. So far, I got:

import itertools

list1 = [1,2,3]
list2 = [1,2,3]
list3 = [1,2,3,4,5,6,7,8,9]

for x, y, in itertools.product(list1, list2):
    print x, y, list3

This returns:

1 1 [1, 2, 3, 4, 5, 6, 7, 8, 9]
1 2 [1, 2, 3, 4, 5, 6, 7, 8, 9]
1 3 [1, 2, 3, 4, 5, 6, 7, 8, 9]
2 1 [1, 2, 3, 4, 5, 6, 7, 8, 9]
2 2 [1, 2, 3, 4, 5, 6, 7, 8, 9]
2 3 [1, 2, 3, 4, 5, 6, 7, 8, 9]
3 1 [1, 2, 3, 4, 5, 6, 7, 8, 9]
3 2 [1, 2, 3, 4, 5, 6, 7, 8, 9]
3 3 [1, 2, 3, 4, 5, 6, 7, 8, 9]

However, I'd like it to return the following:

1 1 1
1 2 2
1 3 3
2 1 4
2 2 5
2 3 6
3 1 7
3 2 8
3 3 9

How can I get to this result?

Kevin
  • 74,910
  • 12
  • 133
  • 166
schlda00
  • 21
  • 3
  • I saw those other posts but as I am a total beginner I did not understand the answers provided there. The answer provided by Kevin is perfect and works like charm for me. Thanks! – schlda00 Dec 30 '15 at 14:31

1 Answers1

5

Iterating through two collections in parallel is conventionally done using zip:

import itertools

list1 = [1,2,3]
list2 = [1,2,3]
list3 = [1,2,3,4,5,6,7,8,9]

for (x, y), z in zip(itertools.product(list1, list2), list3):
    print x, y, z

Result:

1 1 1
1 2 2
1 3 3
2 1 4
2 2 5
2 3 6
3 1 7
3 2 8
3 3 9

Alternatively, if list3 is always going to be [1,2,3... some int], you can discard it entirely and just use enumerate.

import itertools

list1 = [1,2,3]
list2 = [1,2,3]

for idx, (x, y) in enumerate(itertools.product(list1, list2), 1):
    print x, y, idx
Kevin
  • 74,910
  • 12
  • 133
  • 166