繁体   English   中英

汇总文件中的数字

[英]Sum up numbers in a file

myfile = open("file.txt")
lines = myfile.readlines
myfile.close

我被困在这里,在汇总文件数量时遇到问题。 他们是

12
23
34
45
56
67
42
9001

您可以将每行转换为整数,然后使用sum函数获得总和:

print(sum(map(int, open("file.txt"))))

这是一步一步的过程,以实现您的要求。

file = open("numbers.txt", "r") #read the file
file = file.read().splitlines() #create a list where each value is a line of the file
file = list(map(int, file)) #convert each of the values on the list to "int"
print(sum(file)) #sum all the values inside the list
  1. 您需要阅读文件
  2. 创建一个列表,其中每个值都是一行文本
  3. 将列表的所有值“插入”为“ str”时将其转换为“ int”
  4. 汇总列表中的所有值

暂无
暂无

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

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