python - 查找字典列表的总和
问题描述
我有一个列表,其中包含很多看起来像这样的字典(我只插入了前两个):
[
{
"_id": "60ca15162a42482a5fc83bcc",
"name": "Fanta",
"category": "Soft Drinks",
"description": "Fresh Drink",
"price": 14,
"quantity": 104
},
{
"_id": "60ca15162a42482a5fc83bcc",
"name": "Fanta",
"category": "Soft Drinks",
"description": "Fresh Drink",
"price": 16,
"quantity": 104
} ]
我想得到总价。总价看起来是这样的。
total=(14*104)+(16*104)
当列表中有很多字典时,我该怎么做?有什么想法吗?
解决方案
您可以使用sum()
:
lst = [
{
"_id": "60ca15162a42482a5fc83bcc",
"name": "Fanta",
"category": "Soft Drinks",
"description": "Fresh Drink",
"price": 14,
"quantity": 104,
},
{
"_id": "60ca15162a42482a5fc83bcc",
"name": "Fanta",
"category": "Soft Drinks",
"description": "Fresh Drink",
"price": 16,
"quantity": 104,
},
]
total = sum(d["price"] * d["quantity"] for d in lst)
print(total)
印刷:
3120
编辑:要创建一个总计列表:
total = [d["price"] * d["quantity"] for d in lst]
print(total)
印刷:
[1456, 1664]
推荐阅读
- string - 如何在bash中生成随机字符串?
- r - 在 R 中翻译 matlab fminsearchbnd?
- python - 通过自制软件安装的 Tesseract,Anaconda 说没有模块 'pytesseract?
- sql-server - 远程 SQL Server 连接问题
- mysql - 使用进度条从 mysql 数据库下载 blob
- c++ - 如何在函数调用中将整数转换为字符指针
- javascript - 如何在类初始化时从构造函数数据创建对象
- apache - 在 rewriteCond 中匹配 HTTP_HOST?
- autodesk-forge - OSS 存储桶中的 DWG 或其他 2D 文件版本控制
- javascript - 尝试构建可以迭代嵌套数据结构并根据类型生成样式化 HTML 元素的 React 组件