erocoar
erocoar

Reputation: 5893

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'

Upvotes: 4

Views: 836

Answers (2)

timgeb
timgeb

Reputation: 78650

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).

Upvotes: 7

JuniorCompressor
JuniorCompressor

Reputation: 20015

You can read the whole input and use a regular expression:

import sys
import re

numbers = map(int, re.findall(r'\d+', sys.stdin.read()))
print numbers, sum(numbers)

On input

11 22
33

The output is

[11, 22, 33] 66

Upvotes: 1

Related Questions