python-3.x - 如何计算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",",")
。
欢迎所有反馈,我认为这可能很容易解决,但我无法到达那里 - 谢谢。
解决方案
如果我让您正确并以最简单的方式思考,您可以分配一个变量并在每次迭代中将其相加,例如:
res = 0
for i in range(len(List1)):
t = ((int(Dictionary1[List1[i]])*int(Dictionary2[List1[i]])))
res += t
print(res)
编辑:正如@patrick 在这篇文章中建议和讨论的那样,变量名被编辑为sum
推荐阅读
- c++ - 有没有办法同时使用 std::less<> 的转发和自定义比较与 std::set/std::map?
- ios - @ViewBuilder 在使用其他属性初始化时抛出错误
- python - 如何使用 Selenium Python 获取文本颜色
- c - strcmp() 段错误,不知道为什么?
- php - 无法在 GAE/云存储/PHP 上创建大型 zip 文件
- litedb - LiteDB 查询 - 多线程、索引。内存占用
- r - 避免“你想继续吗?[y/N]:' 在 R 中通过自动回答所有行的 y
- ios - 有没有办法在 PHPickerViewController 中预选项目
- python - .desktop 文件中的名称在 tkinter 中不起作用 - python
- typescript - 这个编译问题是否针对 babel-jest 正确提交?