0

I am trying to have a python function that will return all possible ordered combinations between two lists. Ex a = [1, 2, 3] b = [4, 5, 6]

output: 123 126 153 156 423 426 453 456

The number of combinations returned should be 2^n where n is the length of the lists. The lists will always be the same length. The order of the lists must always remain the same. In the example: 1 or 4 must always be in the first position, 2 or 5 must always be in the second position, and 3 or 6 must always be in the third position.

UPDATED I have tried doing list(itertools.combinations(a + b, 3)), however, this returns all combinations including those that I do not want (ex 125. The order must be preserved so that only 1 or 4 can be in the first position, only 2 or 5 can be in the second position, and only 3 or 6 can be in the last position.

My issue is in actually creating the list of possible outputs. Once I have a list I can mess with it to display the way I want. (eventually, I want to output to CSV file).

Rnance
  • 13
  • 3
  • 2
    We would love to know what you have tried. – Austin Mar 05 '19 at 17:14
  • 1
    Welcome to SO. Your question seems too broad. Which part of your process are you having trouble with? Making combinations? Iterating over lists? Combining three single digit integers into one three digit integer? Please take the time to read [ask] and the other links found on that page. and ... [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask), – wwii Mar 05 '19 at 17:22
  • I unmarked this as a duplicate as, reading [combinations between two lists?](https://stackoverflow.com/q/12935194/364696) more carefully, it's not about the same thing. Most of the other related questions aren't either; this question is about selecting a value for a given index from each source `list`, not combining each element from the first list with each element from the second. That is, most other questions would want outputs of `14, 15, 16, 24, 25, 26, ...`, not `123, 126, 153, 156, ...`. – ShadowRanger Mar 05 '19 at 18:42
  • And never mind, found a real duplicate which I apparently answered years ago: [All possible replacements of two lists?](https://stackoverflow.com/q/44593640/364696). Whoops. I can't remark this as a duplicate; can someone else do so? – ShadowRanger Mar 05 '19 at 18:45

1 Answers1

1

A combination of zip (to make the possibilities for each position) and itertools.product (to cycle the possibilities at each position) makes this pretty easy:

from itertools import product

a = [1, 2, 3]
b = [4, 5, 6] 

for result in product(*zip(a, b)):
    print(*result, sep='')

Try it online!

zip is just making pairs of (1, 4), (2, 5) and (3, 6); unpacking those as three arguments to product makes product cycle through each possible selection of a single value from each pair, producing:

123
126
153
156
423
426
453
456
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271