python - Python:如何使用“sum”函数计算列表中数字的总和?
问题描述
我试图计算一个列表中多个数字的总和,但总是出现错误。这些数字是从 txt 中读取的。
数字:
19.18,29.15,78.75,212.10
我的代码:
infile = open("January.txt","r")
list = infile.readline().split(",")
withdrawal= sum(list)
错误:
withdrawal= sum(list)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
解决方案
您需要将每个元素从 转换str
为float
,您可以使用生成器表达式来执行此操作。
with open("January.txt","r") as infile:
data = infile.readline().split(",")
withdrawal = sum(float(i) for i in data)
推荐阅读
- sql - 将多个 Access SQL 结果设置为变量
- python - 将数学函数从 Python 转换为 C++
- firebase - 克隆 Firebase 项目(包括用户帐户)
- wordpress - 通过单击菜单导航到页面末尾
- python - 使用正则表达式在搜索结果中排除 href 链接
- asp.net-core - Autofac 注册封闭类型并在运行时检索它们
- excel - Excel VBA:从多个excel文件中提取数据
- visual-studio-2017 - VS2017 在源代码中出现大量“无法解析符号”错误,但一切正常
- ios - 使用带有 MKOverlay 的图像的内存泄漏崩溃
- javascript - localhost:3000/app.js 而不是 app/www/app.js