首页 > 解决方案 > 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'

标签: python

解决方案


您需要将每个元素从 转换strfloat,您可以使用生成器表达式来执行此操作。

with open("January.txt","r") as infile:
    data = infile.readline().split(",")
    withdrawal = sum(float(i) for i in data)

推荐阅读