首页 > 解决方案 > 如何计算for循环的输出之和

问题描述

我已经构建了一个遍历列表值的 for 循环,将它们作为两个字典的键输入,并将 2 个键值相乘。

打印时,它会在新行上给出每个相乘的值。

我想将这些值加在一起以获得总和,但到目前为止还没有。

#The list and two dictionaries 

List1 = ['coffee', 'tea' , 'cake' , 'scones' ]  

Dictionary1 ={'coffee' :'4', 'tea' :'2' , 'cake' :'6' , 'scones' :'8' }

Dictionary2 = { 'coffee':'25' , 'tea':'18' , 'cake':'45' , 'scones':'30' }


#the for function which runs through the list

for i in range(len(List1)): 
  t = ((int(Dictionary1[List1[i]])*int(Dictionary2[List1[i]]))) 

#now if you print t the following is printed:

100
36
270
240

我想得到这些值的总和,但到目前为止我还没有。

为此,我尝试了 sum(t) ,它会产生错误:

">TypeError: 'int' 对象不可迭代"

我认为这可能是一个连接错误,所以我尝试了 sum(int(t)) 但这不起作用。

我也试过把它变成 list() " x = list(t) 以及用逗号替换行.replace("\n",",")

欢迎所有反馈,我认为这可能很容易解决,但我无法到达那里 - 谢谢。

标签: python-3.xfor-loopsum

解决方案


如果我让您正确并以最简单的方式思考,您可以分配一个变量并在每次迭代中将其相加,例如:

res = 0
for i in range(len(List1)): 
  t = ((int(Dictionary1[List1[i]])*int(Dictionary2[List1[i]])))
  res += t

print(res)

编辑:正如@patrick 在这篇文章中建议和讨论的那样,变量名被编辑为sum


推荐阅读