简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM