简体   繁体   中英

How to calculate the sum of all digits?

I have a document with words and numbers and I have to calculate the sum of all numbers (I am still quite new).

The Error message/Traceback I get is:

line 12, in <module>
    final = final + i
TypeError: unsupported operand type(s) for +: 'int' and 'list'

My code:

file = open("test11.py.txt")
cnt = list()
newcnt = list()
final = 0
import re
for line in file:
    line = line.rstrip()
    num = re.findall('[0-9]+',line)
    if len(num)<1 : continue
    cnt.append(num)
for i in cnt:
    final = final + i
print(final)

Change final = final + i to final += sum(map(int, i)) could work.

The reason is that num is a list , so you get a list named i later whose element is string.

As was pointed out by Yang Liu, the biggest issue in your code resulted from not taking into account that re.findall returns a list of zero or more values. Your code needed to deal with lists and the fact that the elements in the list are string that had to be converted into integers.

Apart from adding the map call to your existing code, another approach would be to use a function to process the results of the re.findall call, and then streamlining your remaining code. If your curious as to what that approach would look like, here is an example implementation.

import re

def do_line_sum(line):
    line_sum = 0
    for str_num in line:
        line_sum += int(str_num)
    return line_sum

file_sum = 0
for line in open("test11.py.txt"):
    file_sum += do_line_sum(re.findall(r"\d+", line))
    
print(total)

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