如果我的文件包含
如何获取每一行的总和,而忽略第一行包含空白元素
这就是我所拥有的,但这只给我这个错误消息
TypeError:+不支持的操作数类型:“ int”和“ str”
file = open(inputFile, 'r')
for line in file:
result = sum(line)
print(result)
答案 0 :(得分:0)
版本1:
with open("input.txt") as f:
for line in f:
result = sum(int(x or 0) for x in line.split(","))
print(result)
这处理空字符串的情况(自int("" or 0) == int(0) == 0
起),虽然很短,但否则不够健壮。
版本2:
with open("input.txt") as f:
for line in f:
total = 0
for item in line.split(","):
try:
total += int(item)
except ValueError:
pass
print(total)
这对于格式错误的输入更为健壮(它将跳过所有无效项,而不是引发异常)。如果您要解析混乱(例如手动输入)的数据,这可能会很有用。
答案 1 :(得分:0)
这不起作用,因为您尝试像这样求和字符串
'10,20,,30'
或这个
'10,20,5,20'
我的解决方案:
import re
regex = re.compile(r',,|,')
with open(file, 'r') as f:
for line in f:
s = 0
for x in regex.split(line):
s += int(x)
print(s)
答案 2 :(得分:0)
我的代码看起来很愚蠢,但是它可以工作,您可以找到另一种方法,让代码看起来更加智能和专业。
def my_function():
file = open("exampleValues","r")
total = 0
for line in file:
a,b,c,d=line.split(",")
if a=='':
a=0
if b=='':
b=0
if c=='':
c=0
if d=='':
d=0
a=int(a)
b = int(b)
c = int(c)
d = int(d)
print(a+b+c+d)
my_function()