[英]Python: How do I sum a line full of integers one by one?
I have several lines full of integers(from a .txt file), and I want to sum every signle integer one by one for each line. 我有几行充满整数(来自.txt文件),并且我想对每个符号整数逐行求和。
Example: 例:
37107287533902102798797998220837590246510135740250 line0 = sum_of_numbers
46376937677490009712648124896970078050417018260538 line1 = sum_of_numbers
74324986199524741059474233309513058123726617309629 .
91942213363574161572522430563301811072406154908250 .
23067588207539346171171980310421047513778063246676 .
89261670696623633820136378418383684178734361726757 .
28112879812849979408065481931592621691275889832738 .
44274228917432520321923589422876796487670272189318 .
47451445736001306439091167216856844588711603153276 .
70386486105843025439939619828917593665686757934951 line9 = sum_of_numbers
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]
You could use something like this to iterate through the lines of your file and sum the numbers. 您可以使用类似的方法遍历文件各行并求和。
with open('file.txt', 'r') as f:
for line in f:
print(sum(int(char) for char in line.strip()))
If there is a chance your lines may not be all digits the you will need to use this instead to check. 如果您的行有可能不是全部数字,则需要使用它来进行检查。
print(sum(int(char) for char in line if char.isdigit()))
# no need for .strip() since \n characters are not a digit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.