计算文件中数字字符串的总和,而数字在随机行中
Calculate sum of string of numbers from a file, while the numbers are in random rows
我有一个包含行中数字的文件,每行中的数字数量是随机的。我需要计算总和。
我的输入是这样的:
63,59,39,5,99,35,56
58,19,35,34,88,55,38,47,90
38,46,33,62,9,58,54,34,37
78,72,25,56,17
我目前的代码是:
def sumIs(file):
line = file.readlines()
lines = [line.split(",") for line in file]
removed = [lines.rstrip('\n') for lines in file]
for i in range(0, len(removed)):
removed[i] = int(removed[i])
a = sum(removed)
return a
出于某种原因,它 returns 是一个 0。虽然它应该是所有数字的总和。
def sumIs(f):
# Open the file
with open(f) as file:
# read each line
lines = file.readlines()
# strip newline characters and split on commas
line_list = [line.rstrip('\n\r').split(",") for line in lines]
# Set up return variable
rv = 0
# Add the sum the integers in each line to the return variable
for line in line_list:
rv += sum(int(x) for x in line)
return rv
print(sumIs('a.txt'))
通过你的例子给出 1439。
假设 file
是一个打开的文件描述符,你可以完全用列表理解来做到这一点:
def sumIs(file):
lines = file.readlines()
return sum([sum([int(val) for val in line.strip("\n").split(",")]) for line in lines])
你会像这样初始化文件:
file = open("path-to-file")
你应该在 sumIs
returns:
之后关闭它
file.close()
另一种方法是传递文件名并处理打开
在 sumIs 中,正如@CDJB 在他们的回答中所做的那样。
我有一个包含行中数字的文件,每行中的数字数量是随机的。我需要计算总和。
我的输入是这样的:
63,59,39,5,99,35,56
58,19,35,34,88,55,38,47,90
38,46,33,62,9,58,54,34,37
78,72,25,56,17
我目前的代码是:
def sumIs(file):
line = file.readlines()
lines = [line.split(",") for line in file]
removed = [lines.rstrip('\n') for lines in file]
for i in range(0, len(removed)):
removed[i] = int(removed[i])
a = sum(removed)
return a
出于某种原因,它 returns 是一个 0。虽然它应该是所有数字的总和。
def sumIs(f):
# Open the file
with open(f) as file:
# read each line
lines = file.readlines()
# strip newline characters and split on commas
line_list = [line.rstrip('\n\r').split(",") for line in lines]
# Set up return variable
rv = 0
# Add the sum the integers in each line to the return variable
for line in line_list:
rv += sum(int(x) for x in line)
return rv
print(sumIs('a.txt'))
通过你的例子给出 1439。
假设 file
是一个打开的文件描述符,你可以完全用列表理解来做到这一点:
def sumIs(file):
lines = file.readlines()
return sum([sum([int(val) for val in line.strip("\n").split(",")]) for line in lines])
你会像这样初始化文件:
file = open("path-to-file")
你应该在 sumIs
returns:
file.close()
另一种方法是传递文件名并处理打开 在 sumIs 中,正如@CDJB 在他们的回答中所做的那样。