在Python词典列表中求和值

时间:2017-12-16 05:17:37

标签: python list dictionary sum

我有这个代码,我试图附加到字典,并在循环终止后,以字典格式打印出名称和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)

1 个答案:

答案 0 :(得分: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)