简体   繁体   English

Python:如何使用“sum” function 来计算列表中数字的总和?

[英]Python: How to use the “sum” function to calculate the sum of numbers in a list?

I'm trying to calculate the sum of multiple numbers in one list, but there always appears an error.我试图计算一个列表中多个数字的总和,但总是出现错误。 These numbers are readed from a txt.这些数字是从 txt 中读取的。

Numbers:数字:

19.18,29.15,78.75,212.10

My code:我的代码:

infile = open("January.txt","r")
list = infile.readline().split(",")
withdrawal= sum(list)

Error:错误:

withdrawal= sum(list)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

You would need to convert each element from str to float , you can do this with a generator expression.您需要将每个元素从str转换为float ,您可以使用生成器表达式来执行此操作。

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

The elements of the list are in str format.列表的元素是str格式。 When they are converted into int or float format, then the sum function will return the sum of the list.当它们转换为intfloat格式时, sum function将返回列表的总和。

This can be done using the map function as following:这可以使用map function来完成,如下所示:

liss=map(float,lis)

Hence:因此:

f=open("January.txt", "r")
lis = f.readline().split(",")
liss=map(float,lis)
withdrawal= sum(liss)
print(withdrawal)

This will produce the desired output.这将产生所需的 output。

Hope this was helpful!希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM