Python | Extract combinational match into two lists

Python Methods and Functions

Method: Using zip () + product ()
These functions can solve this problem and require two steps to complete. In step 1 we find all combinations of elements using product () and as part of step 2 we do a possible conjugation with the result of step 1 using zip () and display the desired result.

# Python3 code to demonstrate how it works
# Extract the combinational mapping into two lists
# using zip () + product ()

from itertools import product

 
# initialize lists

test_list1 = [ 3 , 4 , 5 ]

test_list2 = [ 'x' , 'y' ]

 
# printing original lists

print ( "The original list 1 is:" + str (test_list1))

print ( "The original list 2 is:" + str (test_list2))

  
# Extract combinational sop leaving in two lists
# using zip () + product ()

res = list ( list ( zip (test_list1, ele)) for ele in product (test_list2, repeat = len (test_list1)))

 
# print result

print ( " Mapped Combination result: " + str (res))

Output:

The original list 1 is: [3, 4, 5]
The original list 2 is: ['x', 'y ']
Mapped Combination result: [[(3,' x '), (4,' x '), (5,' x ')], [(3,' x '), (4,' x '), (5,' y ')], [(3,' x '), (4,' y '), (5,' x ')], [(3,' x '), (4 , 'y'), (5, 'y')], [(3, 'y'), (4, 'x'), (5, 'x')], [(3, 'y'), (4, 'x'), (5, 'y')], [(3, 'y'), (4, 'y'), (5, 'x')], [(3, 'y' ), (4, 'y'), (5, 'y')]]





Get Solution for free from DataCamp guru