rookiesix
rookiesix

Reputation: 13

List Comprehension; compacting code to two lines

The basic outline of this problem is to read the file, look for integers using the re.findall(), looking for a regular expression of '[0-9]+' and then converting the extracted strings to integers and summing up the integers.

I have finished the problem, but I would like to go extra and condense the code down to two lines.

This is my original code:

import re

fh = raw_input("Enter filename: ")
#returns regex_sum_241882.txt as default when nothing is entered
if len(fh)<1 : fh = "regex_sum_241882.txt"
file = open(fh)
sums = list()
#goes through each line in the file
for line in file:
    #finds the numbers in each line and puts them in a list
    nums = re.findall('[0-9]+',line)
    #adds the numbers to an existing list
    for num in nums:
        sums.append(int(num))
#sums the list
print sum(sums)

Now here's my current compact code:

import re
lst = list()
print sum(for num in re.findall('[0-9]+',open("regex_sum_241882.txt").read())): int(num))

It doesn't work and gives me SyntaxError: invalid syntax

Can anyone point me in the right direction? I feel I'm doing the same thing, but I'm not sure what the syntaxerror is about.

Upvotes: 1

Views: 176

Answers (1)

Felippe Raposo
Felippe Raposo

Reputation: 431

Try this way:

print sum(int(num) for num in re.findall('[0-9]+', open("regex_sum_241882.txt").read()))

Upvotes: 1

Related Questions