Reputation: 17
I used a regex expression which extracted numbers from some line and this created some list which i combined using the append function how do i combine these sublists into one list
fname=input('Enter file name:')
if len(fname)<1:
fname='regex_sum_42.txt'
fhand=open(fname)
total=0
numlist=list()
for line in fhand:
line.rstrip()
numl= re.findall('([0-9]+)',line )
if len(numl)<1:
continue
numlist.append(numl[0:])
print(numlist)
What i got : [[1,2,3],[4,5]] ,i expected to get [1,2,3,4,5]
Upvotes: 1
Views: 34
Reputation: 40763
You are working too hard: why process the file line by line when you can process the whole file at once?
# Assume file_name is defined
with open(file_name) as stream:
contents = stream.read()
numbers_list = re.findall(r"\d+", contents)
numbers_list = [int(number) for number in numbers_list]
print(numbers_list)
r"\d+"
, which is an alternative form. \d
will match a digit.re.findall()
will return text, which we need to convert to integers if neededUpvotes: 0