4 个解决方案
#1
用split分割每行字符串得到各个数字。然后求和
#2
#!/usr/bin/python3
sum = 0;
with open("num.txt","r") as f:
for l in f.readlines():
ls=l.split(',')
sum += int(ls[1])+int(ls[2])+int(ls[3])
print("sum=",sum)
#3
2楼的方法可行,如果单行求和的话,需要把sum=0定义于for循环体内
for l in f.readlines():
ls=r.split(",")
print(int(ls[1])+int(ls[2])+int(ls[3]))
for l in f.readlines():
ls=r.split(",")
print(int(ls[1])+int(ls[2])+int(ls[3]))
#4
#!/usr/bin/python3
import csv
with open("num.txt","r") as f:
line_sum = list(map(lambda l:sum(map(int,l[1:])), csv.reader(f)))
print(line_sum)
#1
用split分割每行字符串得到各个数字。然后求和
#2
#!/usr/bin/python3
sum = 0;
with open("num.txt","r") as f:
for l in f.readlines():
ls=l.split(',')
sum += int(ls[1])+int(ls[2])+int(ls[3])
print("sum=",sum)
#3
2楼的方法可行,如果单行求和的话,需要把sum=0定义于for循环体内
for l in f.readlines():
ls=r.split(",")
print(int(ls[1])+int(ls[2])+int(ls[3]))
for l in f.readlines():
ls=r.split(",")
print(int(ls[1])+int(ls[2])+int(ls[3]))
#4
#!/usr/bin/python3
import csv
with open("num.txt","r") as f:
line_sum = list(map(lambda l:sum(map(int,l[1:])), csv.reader(f)))
print(line_sum)