combining sublists created from regex expressions

Question:

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]

Asked By: Kojo Nyarko

||

Answers:

One solution to flatten your list of lists.

sum(numlist, [])
Answered By: 0x0fba

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)

Notes

  • I used the regular expression r"d+", which is an alternative form. d will match a digit.
  • By default, re.findall() will return text, which we need to convert to integers if needed
Answered By: Hai Vu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.