rain-m
rain-m

Reputation: 55

Converting a list of str into list of int python

I have the following input:

669  866  147
 15  881  210
662   15   70

Using .split('\n') on it, I am able to get a list of 3 strings. Then I would like to break each string to a list of strings and then convert those to int. The code I'm trying to use for this so far is

for tr in numbers:
    tr = tr.split()
    tr = list(map(int, tr))

However, after the for loop closes nothing happened to the original list, so if I run this command print(type(numbers[0])) it returns <class 'str'>.

I am guessing this is due to the operation happening inside the loop so outside it nothing changed, so how would I go about making it so the original list updates too?

Upvotes: 1

Views: 253

Answers (4)

Tyson
Tyson

Reputation: 424

The Pythonic way would be to use a list comprehension - avoiding enumeration/indexing, mutation and a new variable in the scope:

>>> numbers = ["669  866  147", " 15  881  210", "662   15   70"]
>>> numbers = [map(int, tr.split()) for tr in numbers]
>>> numbers
[[669, 866, 147], [15, 881, 210], [662, 15, 70]]

Some people avoid the map builtin, in which case you could substitute the second line with this:

numbers = [[int(n) for n in tr.split()] for tr in numbers]

Upvotes: 0

Leo
Leo

Reputation: 288

A one-liner for this could be like this:

In [6]: numbers = "669 866 147\n15 881 210\n662 15 70"

In [7]: [[int(y) for y in x.split()] for x in numbers.split('\n')]
Out[7]: [[669, 866, 147], [15, 881, 210], [662, 15, 70]]

You can assign In [7] directly back to numbers, or into a separate new variable.

Upvotes: 2

Ari Gold
Ari Gold

Reputation: 1548

import re
numbers = ["669  866 ASSASSA 147", " 15  881  210", "662   15   70"]
numbers = [[int(_str) for _str in re.findall(r"\d+", o)] for o in numbers]
print numbers
# [[669, 866, 147], [15, 881, 210], [662, 15, 70]]

Upvotes: 0

Anshul Goyal
Anshul Goyal

Reputation: 76887

You will have to explicitly set the lists back to the numbers list, right now, you are only manipulating a variable tr with re-assignment, so the original list doesn't get affected. Try this instead

>>> numbers = ["669  866  147", " 15  881  210", "662   15   70"]
>>> for idx, tr in enumerate(numbers):
...     tr = tr.split()
...     numbers[idx] = list(map(int, tr))
... 
>>> numbers
[[669, 866, 147], [15, 881, 210], [662, 15, 70]]

Upvotes: 2

Related Questions