python处理txt文件
阿神
阿神 2017-04-17 17:33:08
0
2
369

我现在有个txt文件的格式如下:
167

19 167

167

21 147

175 21 147

175 16 108

175 123 16 108

175 123 10 108

36 123

我现在想用python将其每行的各个数相加,得到每一行都有一个和,结果应该是这样:
167
186
167
168
我需要这样的结果,但是现在发现问题在于每行的列数是不固定的,就不知道怎么得出这样的结果了。orz

阿神
阿神

闭关修行中......

reply all (2)
左手右手慢动作
# coding:utf-8 # 每行求和 def addEachLine(line): values = line.split() values = [int(v) for v in values if v.strip()] return sum(values) def main(): result = [] with open("input.txt") as f: buf = f.read() lines = buf.splitlines() lines = [l for l in lines if l.strip()] # 对拆分的每一行进行计算 for l in lines: result.append(addEachLine(l)) # 打印结果 for r in result: print r if __name__ == '__main__': main()

输出
167
186
167
168
343
299
422
416
159

    迷茫

    读出每行数据是一个字符串如 str=

    str='175 123 10 108' # 通过切割拆分并转换为int的-》 [175, 123, 10, 108] arr= map(int,str.split(' ')) # 对int列表求和-》416 sum(arr)
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!