user2958130
user2958130

Reputation: 33

Turn a List of Str into a List of Int (Python)

I need to turn a list of strings into a list of integers. I've searched for this question but I don't think people have had the same problem I've had.

Lets say I have a list of strings: List1 = ['1 2 3 4 5', '6 7 8 9 10', '11 12 13 14 15']

How would I turn that into: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] ?

I'm confused how to do this because instead of ['1', '2', '3' etc...] there are about 5 numbers in one string.

Upvotes: 3

Views: 225

Answers (1)

chepner
chepner

Reputation: 531055

First, join each element of List1 to form a single, space-separated string. Then split that and convert each element of the resulting list to an integer.

>>> List1 = ['1 2 3 4 5', '6 7 8 9 10', '11 12 13 14 15']
>>> [ int(x) for x in ' '.join(List1).split()]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

You can also use a nested for with the list comprehension:

>>> [ int(x) for y in List1 for x in y.split() ]

You parse each for expression in the same order as a regular nested for loop.

Upvotes: 4

Related Questions