假设我有 3 部不同的词典:
dict1 = {
"A": "a"
}
dict2 = {
"B": "b",
"C": "c",
"D": "d",
"E": "e"
}
dict3 = {
"F": "f",
"G": "g"
}
我想计算这些字典的乘积(不包括 dict2
和 dict3
之间的乘积),并将键与 _
连接的键和值结合起来和值 ' and '
所需的输出将是单个字典:
{
# dict1 x dict2
"A_B": "a and b",
"A_C": "a and c",
"A_D": "a and d",
"A_E": "a and e",
# dict1 x dict3
"A_F": "a and f",
"A_G": "a and g",
# dict1 x dict2 x dict3
"A_B_F": "a and b and f",
"A_B_G": "a and b and g",
"A_C_F": "a and c and f",
"A_C_G": "a and c and g",
"A_D_F": "a and d and f",
"A_D_G": "a and d and g",
"A_E_F": "a and e and f",
"A_E_G": "a and e and g"
}
我查看了 itertools
的文档但我无法理解如何获得所需的输出。
最佳答案
完成这项工作的函数是itertools.product
.
首先,这是打印乘积 dict1 x dict2 x dict3
的方法:
for t in product(dict1.items(), dict2.items(), dict3.items()):
k, v = zip(*t)
print("_".join(k), "-", " and ".join(v))
输出:
A_B_F - a and b and f
A_B_G - a and b and g
A_C_F - a and c and f
A_C_G - a and c and g
A_D_F - a and d and f
A_D_G - a and d and g
A_E_F - a and e and f
A_E_G - a and e and g
现在,只需填充一个 result
字典:
result = {}
for t in product(dict1.items(), dict2.items(), dict3.items()):
k, v = zip(*t)
result["_".join(k)] = " and ".join(v)
您现在可以将 dict1 x dict2
和 dict1 x dict3
产品添加到该字典中,计算起来更简单。
根据@ShadowRanger 的评论,这里是一个完整的片段:
import itertools
import pprint
dict1 = {
"A": "a"
}
dict2 = {
"B": "b",
"C": "c",
"D": "d",
"E": "e"
}
dict3 = {
"F": "f",
"G": "g"
}
result = {}
for dicts in ((dict1, dict2), (dict1, dict3), (dict1, dict2, dict3)):
for t in itertools.product(*(d.items() for d in dicts)):
k, v = zip(*t)
result["_".join(k)] = " and ".join(v)
pprint.pprint(result)
输出:
{'A_B': 'a and b',
'A_B_F': 'a and b and f',
'A_B_G': 'a and b and g',
'A_C': 'a and c',
'A_C_F': 'a and c and f',
'A_C_G': 'a and c and g',
'A_D': 'a and d',
'A_D_F': 'a and d and f',
'A_D_G': 'a and d and g',
'A_E': 'a and e',
'A_E_F': 'a and e and f',
'A_E_G': 'a and e and g',
'A_F': 'a and f',
'A_G': 'a and g'}
关于python - 计算 3 个字典的乘积并连接键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55636895/