1

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?

4 Answers 4

2

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]]
Sign up to request clarification or add additional context in comments.

4 Comments

Works perfectly, thank you for explaining as well I perfectly understand now, much appreciated!
@AngelosH Happy to help, don't forget to accept and upvote the answer :)
Generally more idiomatic to use a list comp: numbers[idx] = [int(n) for n in tr.split()]
@BenHoyt Agreed, though I just wanted to do minimal number of changes so its easier to understand.
2

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.

1 Comment

Yep this works very nicely too, thanks for the one-liner!
0
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]]

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.