Kenneth
Kenneth

Reputation: 45

Python How to get integers from the list?

I have a list with integers with white space in between. I'd like to retrieve all those individual integer and make a new list with an index.

>>> x = ['1 2 3 4']
>>> type(x)
<class 'list'>
>>> len(x)
1

I want to convert the list into

>>> x = [1, 2, 3, 4]
>>> type(x)
<class 'list'>
>>> len(x)
4

I'm trying with split, it didn't work. How do I do the conversion?

Upvotes: 0

Views: 11904

Answers (3)

Aaditya Ura
Aaditya Ura

Reputation: 12669

You can use lambda and map something like this:

a = ['1 2 3 4']


print(list(map(lambda x:list(map(lambda y:int(y),x.split())),a)))

output:

[[1, 2, 3, 4]]

Upvotes: -1

NPE
NPE

Reputation: 500257

Here is one straightforward way to do it:

>>> map(int, x[0].split())
[1, 2, 3, 4]

Here:

  • x[0] converts ['1 2 3 4'] into '1 2 3 4';
  • .split() converts it into ['1', '2', '3', '4'];
  • map(int, ...) converts it into [1, 2, 3, 4].

That said, it's not totally clear why you have a list in the first place, given that it appears to only have one element (a string of space-separated numbers).

Upvotes: 3

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

x = ['1 2 3 4']
final_x = [int(i) for i in x[0] if i.isdigit()]

Output:

[1, 2, 3, 4]

Upvotes: -1

Related Questions