Python:如何逐行求一行整数?

时间:2015-12-03 12:32:32

标签: python python-3.x integer sum line

我有几行整数(来自.txt文件),我想为每一行逐一求和每个符号整数。

示例:

37107287533902102798797998220837590246510135740250 line0 = sum_of_numbers
46376937677490009712648124896970078050417018260538 line1 = sum_of_numbers
74324986199524741059474233309513058123726617309629 .
91942213363574161572522430563301811072406154908250 .
23067588207539346171171980310421047513778063246676 .
89261670696623633820136378418383684178734361726757 .
28112879812849979408065481931592621691275889832738 .
44274228917432520321923589422876796487670272189318 .
47451445736001306439091167216856844588711603153276 .
70386486105843025439939619828917593665686757934951 line9 = sum_of_numbers 

2 个答案:

答案 0 :(得分:2)

f = open('foo.txt', 'r')

def sum_line(line):
  return sum(int(c) for c in line.strip())

line_sums = [sum_line(line) for line in f]

答案 1 :(得分:0)

你可以使用这样的东西来迭代文件的行并总结数字。

with open('file.txt', 'r') as f:
    for line in f:
        print(sum(int(char) for char in line.strip()))

如果您的行可能不是所有数字,则需要使用此代码进行检查。

print(sum(int(char) for char in line if char.isdigit()))
# no need for .strip() since \n characters are not a digit