在Python词典列表中求和值

问题描述 投票:0回答:1

我有这个代码,我试图附加到字典,并在循环终止后,打印出字典格式的名称和saved_this_month,再打印出saved_this_month的总和。后一部分我遇到了问题,在这种情况下,是total_savings变量。我想我试图将index的值拉到位置1(金额)并总结它们,但很明显,我错了。

有任何想法吗?谢谢。

savings_list = []

while True:
    bank = input('Enter the name of the bank:')
    savings_amount = float(input('Enter the amount saved:'))

    savings_list.append({
        "name": bank,
        "saved_this_month": savings_amount
        })
    total_savings = sum(savings_list[1]) **this is the prob line I think**

    cont = input('Want to add another? (Y/N)')
    if cont == 'N':
        break;

print(savings_list)
print(total_savings)
python list dictionary sum
1个回答
2
投票

如果你想要做的只是输入的储蓄金额,为什么不使用while循环外部的变量呢?

savings_list = []
total_savings = 0  # Define out here

while True:
    bank = input('Enter the name of the bank:')
    savings_amount = float(input('Enter the amount saved:'))

    savings_list.append({
        "name": bank,
        "saved_this_month": savings_amount
        })
    total_savings += savings_amount  # just a simple sum

    cont = input('Want to add another? (Y/N)')
    if cont == 'N':
        break;

print(savings_list)
print(total_savings)

但是,如果您希望在加载savings_list之后想要计算总和,则需要将dicts列表转换为sum知道如何处理的内容列表。尝试列表理解(编辑:或者,更好的是,generator statement):

total_savings = sum(x["saved_this_month"] for x in savings_list)

展开列表理解:

a = []
for x in savings_list:
    a.append(x["saved_this_month"])
total_savings = sum(a)
© www.soinside.com 2019 - 2024. All rights reserved.