简体   繁体   English

汇总文件中的数字

[英]Sum up numbers in a file

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

I am stuck here, having problems sum up numbers in file. 我被困在这里,在汇总文件数量时遇到问题。 They are 他们是

12
23
34
45
56
67
42
9001

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

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

This is a step by step process in order to achieve what you're asking for. 这是一步一步的过程,以实现您的要求。

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. You need to read the file 您需要阅读文件
  2. Create a list where each of the values is a line of the text 创建一个列表,其中每个值都是一行文本
  3. Convert all the values of the list to "int" as they're "inserted" as "str" 将列表的所有值“插入”为“ str”时将其转换为“ int”
  4. Sum all the values inside the list 汇总列表中的所有值

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

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