How to receive a vector whose values are separated by spaces

1

I'm starting in python and I use a site that has several problems for resolution, in it the vectors and arrays are passed with values separated by a space and not comma. For example: v = 1 2 3 43.

I know I can get this value in the input and leave it as a string, the question is how to make that string into a vector. I would like to know if there is any function that can convert, because if I am to "handle" this input I lose efficiency.

    
asked by anonymous 28.07.2014 / 15:37

3 answers

2

If this is what you want, to receive a string with number and then convert them, use the following code:

>>> s = "1 2 3 56 88"
>>> map(int, s.split())
[1, 2, 3, 56, 88]

Explaining: s.split() transforms a string into a vector, using the parameter as a delimiter. The default value of the delimiter (which is hidden) is space.

After that, it is passed as input to the map function. It simply performs a function for each element in the list. In this case, it will pass to the function int , which converts a string to integer.

Note that it will generate a ValueError ception exception if it does not successfully convert.

    
28.07.2014 / 18:38
1

Well let's go

Is it possible for you to install the numpy module?

The numpy is highly recommended when you start working with vectors and array, it actually breaks a giant branch.

Your problem would be solved like this:

import numpy as np

v = "1 2 3 43"
teste=v.split() 
vetor = np.asarray(teste)
    
28.07.2014 / 18:35
0

I do not know if this is what you want, but I hope it helps: a = map (int, input (). split ()) In this case the vector a receives a list of ints separated by space, comma, bar, etc.

    
24.04.2017 / 23:48