python - 计算 3 个字典的乘积并连接键和值

标签 python

假设我有 3 部不同的词典:

dict1 = {
  "A": "a"
}

dict2 = {
  "B": "b", 
  "C": "c",
  "D": "d", 
  "E": "e"
}

dict3 = {
  "F": "f", 
  "G": "g"
}

我想计算这些字典的乘积(不包括 dict2dict3 之间的乘积),并将键与 _ 连接的键和值结合起来和值 ' 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 dict2dict1 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/

相关文章:

python - 在python中将整数转换为大端二进制文件

python - 动态定义具有不同签名的函数

python - 导入错误 : No module named bottle

python - 从 VS Code 使用 Python 部署 Azure 函数,函数在 WEBSITE_RUN_FROM_PACKAGE 应用程序设置后消失

python - PyCharm 导入方式与系统命令提示符 (Windows) 有何不同

python - 无法使用 Python 打印请求响应

Pythonic 方式查找与嵌套字典关联的键

Python splitter 按标签属性选择

python - 如何在 Python 中获取 unicode 月份名称?

python - 502 Bad Gateway upstream 在使用 flask、uWSGI、nginx 从上游读取响应 header 时过早关闭连接