简体   繁体   English

映射两个嵌套列表的排列

[英]Permutations of mapping two nested lists

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.我想获取将 listA 中的列表映射到相同索引的 listB 中的列表的所有排列,并以字典列表或元组列表的形式进行处理。 An example of my desired output is:我想要的 output 的一个例子是:

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.我尝试过使用 itertools 产品和排列,但没有得到想要的结果。 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!如果有人能提出解决这个问题的好方法,我将不胜感激!

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:您可以使用递归生成器 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: 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'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM