查找字典列表的总和

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

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

编辑:要创建一个带有总计的列表:

印刷:

total = [d["price"] * d["quantity"] for d in lst]
print(total)


以上是查找字典列表的总和的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>