Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of strings to int

I have a list of strings that I want to convert to int, or have in int from the start.

The task is to extract numbers out of a text (and get the sum). What I did was this:

for line in handle:
    line = line.rstrip()
    z = re.findall("\d+",line)
    if len(z)>0:
        lst.append(z)
print (z)

Which gives me a list like [['5382', '1399', '3534'], ['1908', '8123', '2857']. I tried map(int,... and one other thing, but I get errors such as:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
like image 642
erocoar Avatar asked Feb 08 '23 02:02

erocoar


1 Answers

You can use a list comprehension:

>>> [[int(x) for x in sublist] for sublist in lst]
[[5382, 1399, 3534], [1908, 8123, 2857]]

or map

>>> [map(int, sublist) for sublist in lst]
[[5382, 1399, 3534], [1908, 8123, 2857]]

or just change your line

lst.append(z)

to

lst.append(map(int, z))

The reason why your map did not work is that you tried to apply int to every list of your list of lists, not to every element of every sublist.

update for Python3 users:

In Python3, map will return a map object which you have to cast back to a list manually, i.e. list(map(int, z)) instead of map(int, z).

like image 138
timgeb Avatar answered Feb 12 '23 02:02

timgeb