0

I have my user input input in the form of nested list. I want to make combinations out of it and it's like as follows:

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

Zipping it using zip function in python so that traversing would be easy.

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

Tree structure to be traversed ex:
                        1
               /        |         \
               2        5         8
              / | \    /| \     /  | \
             3  6  9   3 6 9    3   6  9 

Expected ouput

1,2,3
1,2,6
1,2,9
1,5,3
1,5,6
1,5,9
...
...
7,8,9

I'm not getting how to achieve such combinations using dictionaries or maps or if there is other way to do this please suggest.

user7422128
  • 902
  • 4
  • 17
  • 41

2 Answers2

2

You can use the itertools.product function:

from itertools import product

l = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
for p in product(*l):
    print(p)

Output:

(1, 2, 3)
(1, 2, 6)
(1, 2, 9)
(1, 5, 3)
(1, 5, 6)
(1, 5, 9)
...
(7, 8, 9)

Calling the function like this (without any additional params) returns the cartesian product of the 3 "sets".

cs95
  • 379,657
  • 97
  • 704
  • 746
2

People may introduce you itertools as what Hunter McMillen commented. You can find better solution from the website he provided.

Here is a simple code that also does the same job.

A = l = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
for i in A[0]:
    for j in A[1]:
        for k in A[2]:
            print([i, j, k])
Mr_U4913
  • 1,294
  • 8
  • 12