Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change a string of integers separated by spaces to a list of int

How do i make something like

x = '1 2 3 45 87 65 6 8'  >>> foo(x) [1,2,3,45,87,65,6,8] 

I'm completely stuck, if i do it by index, then the numbers with more than 1 digit will be broken down. Help please.

like image 841
Spock Avatar asked Oct 24 '13 01:10

Spock


People also ask

How do you convert space separated into list in Python?

Use an input() function to accept the list elements from a user in the format of a string separated by space. Next, use a split() function to split an input string by space. The split() method splits a string into a list.

How do you input integers separated by space?

Use a simple for loop. int i, n, arr[100]; scanf("%d", &n); for (i = 0; i < n; ++i) scanf("%d", &arr[i]); The above code snippet would do.


1 Answers

The most simple solution is to use .split()to create a list of strings:

x = x.split() 

Alternatively, you can use a list comprehension in combination with the .split() method:

x = [int(i) for i in x.split()] 

You could even use map map as a third option:

x = list(map(int, x.split())) 

This will create a list of int's if you want integers.

like image 187
tijko Avatar answered Sep 20 '22 14:09

tijko