Python中如何实现两个含字典元素的列表对应数值相乘?
Python实现两个同结构列表字典的数值乘积运算
实现代码
基础写法(可读性高)
list1 = [{'the': '0.181'}, {'to': '0.115'}, {'a': '0.093'}, {'of': '0.084'}, {'and': '0.078'}] list2 = [{'the': '1.010'}, {'to': '1.010'}, {'a': '1.000'}, {'of': '1.102'}, {'and': '1.228'}] result = [] # 同步遍历两个列表的同位置字典 for dict1, dict2 in zip(list1, list2): # 获取当前位置字典的唯一键 current_key = next(iter(dict1.keys())) # 字符串转浮点数计算乘积,再转回字符串格式(这里保留3位小数,可按需调整) product_value = float(dict1[current_key]) * float(dict2[current_key]) result.append({current_key: f"{product_value:.3f}"}) print(result)
简写写法(列表推导式)
result = [ {next(iter(d1.keys())): f"{float(d1[next(iter(d1.keys()))]) * float(d2[next(iter(d1.keys()))]):.3f}"} for d1, d2 in zip(list1, list2) ]
输出结果
运行后得到符合要求的结构:
[{'the': '0.183'}, {'to': '0.116'}, {'a': '0.093'}, {'of': '0.093'}, {'and': '0.096'}]
说明
- 代码依赖两个列表长度一致、同位置字典的键完全匹配的前提,和题目给出的结构要求一致
- 乘积保留的小数位数可通过调整格式化参数修改,比如将
.3f改为.4f即可保留4位小数,不需要固定精度也可以直接用str(product_value)输出完整计算结果
内容的提问来源于stack exchange,提问作者lo7
相关产品推荐
相关产品推荐

