Permutations of mapping two nested lists

Viewed 96

I have two nested lists which are in ascending order of the length of the list. For example:

listA= [[1],[2],[3,4],[5,6]]
listB= [[A],[B],[C,D],[E,F]]

I want to get all permutations of mapping the lists in listA to the list in listB of the same index and have it in the form of a list of dictionaries or a list of tuples would be fine. An example of my desired output is :

dict1 = { 1->A,2->B,3->C,4->D,5->E,6->F}
dict2 = { 1->A,2->B,3->D,4->C,5->E,6->F}
dict3 = { 1->A,2->B,3->C,4->D,5->F,6->E}
dict4 = { 1->A,2->B,3->D,4->C,5->F,6->E}

I've tried using itertools product and permutations but I didn't get the desired results. My current approach is to get the permutation of mappings of each list pair then to iteratively create each possible dictionary but it is not a solution I am happy with. If anyone can suggest a good approach to this problem I'd greatly appreciate it!

2 Answers

I think this is what you want:

import itertools as it
listA= [[1],[2],[3,4],[5,6]]
listB= [['A'],['B'],['C','D'],['E','F']]

result = []
for i in range(len(listA)):
    result.append(list(it.product(listA[i], listB[i])))

print(result)
#[[(1, 'A')], [(2, 'B')], [(3, 'C'), (3, 'D'), (4, 'C'), (4, 'D')], [(5, 'E'), (5, 'F'), (6, 'E'), (6, 'F')]]

Alternatively, if you want all the tuples in a 1D list:

result = []
for i in range(len(listA)):
    result.extend(list(it.product(listA[i], listB[i])))

#[(1, 'A'), (2, 'B'), (3, 'C'), (3, 'D'), (4, 'C'), (4, 'D'), (5, 'E'), (5, 'F'), (6, 'E'), (6, 'F')]

You can use a recursive generator function:

from itertools import permutations as perm
def get_combos(d, c = []):
  if not d:
     yield c
  else:
     a, b = d[0]
     for i in perm(a):
        yield from get_combos(d[1:], c+[*zip(i, b)])

listA= [[1],[2],[3,4],[5,6]]
listB= [['A'],['B'],['C','D'],['E','F']]
r = [dict(i) for i in get_combos(list(zip(listA, listB)))]

Output:

[{1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F'}, 
 {1: 'A', 2: 'B', 3: 'C', 4: 'D', 6: 'E', 5: 'F'}, 
 {1: 'A', 2: 'B', 4: 'C', 3: 'D', 5: 'E', 6: 'F'}, 
 {1: 'A', 2: 'B', 4: 'C', 3: 'D', 6: 'E', 5: 'F'}]
Related