You have to convert the items of the (nested) list from str
to int
. You can do so in a single nested generator expression using the sum
builtin function:
>>> sum(int(x) for line in filehandle for x in re.findall(r"\d+", line))
751
Or without nesting, using read()
to get the entire content of the file (if it's not too big):
>>> sum(int(x) for x in re.findall(r"\d+", filehandle.read()))
751
Or using map
instead of a generator expression:
>>> sum(map(int, re.findall(r"\d+", filehandle.read())))
751
Or if you want the sums per line (map
version left as an exercise to the reader):
>>> [sum(int(x) for x in re.findall(r"\d+", line)) for line in filehandle]
[606, 90, 0, 55]
(When you try those in the interactive shell, remember that the file will be "exhausted" after each of those, so you will have to re-open the file before testing the next one. Also note that using \d+
you might get surprising results if your file contains e.g. floating point numbers or IP addresses.)