2

I have a problem. I would like to convert a list of strings with 594 elements, among them many empty, to a list of integers. I already looked up many answers here, but neither list comprehensions, neither map function seems to work. My command prompt simply says int argument must be a string or a number, not a list.

Here is my code:

fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "regex_sum_317625.txt"
fh = open(fname)

import re
numlist = list()

for line in fh:
    line = line.rstrip()
    numbers = re.findall('[0-9]+', line)
    numlist.append(numbers)

print numlist
listlength = len(numlist)
print listlength

intlist = [int(nums) for nums in numlist]
print intlist

I tried many ways, but the problem always is that I try to do an operation on a list which is not allowed. Could you please help me, what should I do?

Redbird
  • 25
  • 4

1 Answers1

4

The approaches you mentioned should work, but you're not building your data correctly; you don't have a list of strings but a list of lists - re.findall returns a list:

numbers = re.findall('[0-9]+', line)
numlist.append(numbers) # appending a list to numlist

You should instead extend numlist with the results of re.findall using the extend method of the list:

numlist.extend(numbers) 

The list.extend method will

extend the list by appending all the items in the given list.


Since you're already familiar with comprehensions, you might as well use a comprehension in place of the for loop:

with open(fname) as fh:
    int_list = [int(item) for line in fh for item in re.findall('[0-9]+', line)]

I noticed, you did not call the close method of your file object fh. You can let Python do the cleanup for you by opening the file with a context manager, using the with statement.

See How to open a file using the open with statement to learn more about this.

Community
  • 1
  • 1
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139