[英]Summing values in Python list of dictionaries
我在尝试添加到字典的地方有此代码,在循环终止后,以字典格式打印名称和saved_this_month
,并打印出saved_this_month
的总和。 在这种情况下,我的后半部分与total_savings变量有关。 我想我试图在位置1中提取index
值(金额)并求和,但是显然,我错了。
有任何想法吗? 谢谢。
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)
如果您要做的就是将输入的节省金额相加,为什么不使用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
知道如何处理的内容的列表。 尝试列表理解( EDIT或更好的是generator语句 ):
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.