Python 3.x 如何计算for循环的输出之和

Python 3.x 如何计算for循环的输出之和,python-3.x,for-loop,sum,Python 3.x,For Loop,Sum,我构建了一个for循环,它遍历列表中的值,将它们作为两个字典的键输入,并将这两个键值相乘 打印时,它会在新行上给出每个相乘的值 我想把这些值加在一起,得到一个综合的总数,但到目前为止还不能 #The list and two dictionaries List1 = ['coffee', 'tea' , 'cake' , 'scones' ] Dictionary1 ={'coffee' :'4', 'tea' :'2' , 'cake' :'6' , 'scones' :'8' }

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

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

我想把这些值加在一起,得到一个综合的总数,但到目前为止还不能

#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
我想得到这些值的总和,但到目前为止我还不能得到

#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),并将行替换为逗号
。替换(“\n”,“,”)


欢迎所有反馈,我认为这可能很容易解决,但我只是没能做到-谢谢。

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

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

print(res)

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

错误是不言自明的:
TypeError:“int”对象在执行
t
时不可iterable。这意味着
t
只是一个单数int值。需要一个iterable进行操作

您需要为每次迭代添加int:

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

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

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


# accumulate your values into s
s = 0
for i in range(len(List1)): 
  t = ((int(Dictionary1[List1[i]])*int(Dictionary2[List1[i]]))) 
  s += t

print(s) # print sum
产出:

646
但是,您也可以创建生成器并使用该函数:

print (sum ( int(Dictionary1[a])*int(Dictionary2[a]) for a in List1))

下面是一个列表,它可以完成这项工作

total = sum(int(Dictionary1[x]) * int(Dictionary2[x]) for x in List1)
输出:

646

如果需要澄清,
res+=t
表示
res=res+t
。由于这是一个基本问题,读者可能不熟悉+=notation。