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'
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With