0

How to combine 2 lists in such a way that each element in list 2 is combined with the elements in list 1 so that “a” combines with only one element in list 1 in each iteration then “b” combines with only two elements in the list 1 in each iteration.

list1= [1,2,3]

list2= [‘a’,‘b’,‘c’,‘d’,‘e’]

dict_list_2 = {‘a’ : 1 , ‘b’ : 2 , ‘c’ : 3 , ‘d’ : 4 , ‘e’ :5}

Expected Output: ('a',1) (a ,2 ) (a , 3) (b , 1 ,2) (b , 1 ,3) (b , 2 ,3) (b , 1 ,1) (b , 2 ,2) (b , 3 ,3) – 

enter image description here

Setareh
  • 13
  • 2
  • 1
    Does this answer your question? [How do I combine two lists into a dictionary in Python?](https://stackoverflow.com/questions/7271385/how-do-i-combine-two-lists-into-a-dictionary-in-python) – RJ Adriaansen Nov 07 '21 at 18:24
  • 1
    Does this answer your question? [How do I convert two lists into a dictionary?](https://stackoverflow.com/questions/209840/how-do-i-convert-two-lists-into-a-dictionary) – Rivers Nov 07 '21 at 18:28

1 Answers1

0

Assuming you want all combinations with replacement from list1:

import itertools

list1= [1,2,3]
list2= list("abcde")
dict_list_2 = {"a" : 1 , "b" : 2 , "c" : 3 , "d" : 4 , "e" :5}

[(letter,) + product
 for letter in list2
 for product in itertools.product(list1, repeat=dict_list_2[letter])]

# out:
[('a', 1),
 ('a', 2),
 ('a', 3),
 ('b', 1, 1),
 ('b', 1, 2),
 ('b', 1, 3),
 ('b', 2, 1),
 ('b', 2, 2),
 ('b', 2, 3),
 ('b', 3, 1),
 ('b', 3, 2),
 ('b', 3, 3),
 ('c', 1, 1, 1),
 ('c', 1, 1, 2),
 ('c', 1, 1, 3),
 ('c', 1, 2, 1),
...
mcsoini
  • 6,280
  • 2
  • 15
  • 38