gpt4 book ai didi

python - 查找字典列表的总和

转载 作者:行者123 更新时间:2023-12-04 00:49:02 26 4
gpt4 key购买 nike

我有一个包含很多字典的列表,看起来像这样(我只插入了前两个):

[
{
"_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]

关于python - 查找字典列表的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68018094/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com