从两个不同的字典中获取所有组合

时间:2018-11-04 03:24:56

标签: python list dictionary itertools

我试图通过仅更改存储为键的值的前两个元素来获取下面两个词典的所有组合。同样对于信息来说,每个值都是该键的首选项。因此在dic中,每个键都有三个首选项,在dic b中,每个键都有四个首选项。我只是想通过更改或交换两个词典中键的前两个首选项来获得所有组合。

a={"ad":["tau","guru","addha"],
"bigd":["tau","guru","addha"],
"lugd":["tau","guru","addha"],
"df":["addha","tau","guru"]}

b={"tau":["ad","bigd","lugd",'df'],
"guru":["bigd","ad",'df',"lugd"],
 "addha":["lugd",'df',"bigd","ad"]}

因此,一种组合是当您更改a [“ ad”]中的前两个元素而其余元素相同时。

a={"ad":["guru","tau","addha"],
"bigd":["tau","guru","addha"],
"lugd":["tau","guru","addha"],
"df":["addha","tau","guru"]}

b={"tau":["ad","bigd","lugd",'df'],
"guru":["bigd","ad",'df',"lugd"],
 "addha":["lugd",'df',"bigd","ad"]}

因此,仅通过更改或交换键的前两个首选项来获得所有组合。

我的代码在以下位置:

a={"ad":["tau","guru","addha"],
"bigd":["tau","guru","addha"],
"lugd":["tau","guru","addha"],
"df":["addha","tau","guru"]}

b={"tau":["ad","bigd","lugd",'df'],
"guru":["bigd","ad",'df',"lugd"],
 "addha":["lugd",'df',"bigd","ad"]}
from itertools import permutations, product

def permute_first2(a):
    b=[]
    permutes=list(list(p) for p in permutations(a[:2]))
    for i in permutes:
        b.append(i+a[2:])
    return b



length_a=len(a.keys())
length_b=len(b.keys())
items_a=list(a.keys())
items_b=list(b.keys())

a_variants = [dict(zip(items_a, values)) 
                 for values in product(permute_first2(items_b), repeat=3)]
b_variants = [dict(zip(items_b, values)) 
                 for values in product(permute_first2(items_a), repeat=3)]


all_variants = product(a_variants, b_variants)
for va, vb in all_variants:
    print("a:", va, "\nb:", vb, "\n")

0 个答案:

没有答案