Kojo Nyarko
Kojo Nyarko

Reputation: 17

combining sublists created from regex expressions

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

Answers (2)

Hai Vu
Hai Vu

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)

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

Upvotes: 0

0x0fba
0x0fba

Reputation: 1620

One solution to flatten your list of lists.

sum(numlist, [])

Upvotes: 2

Related Questions