How to receive a vector, whose values are separated by spaces

Asked

Viewed 3,271 times

1

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

I know I can receive this value in the input and leave it as a string, the question is how to transform this string into an array. I wonder if there is any function I can convert, because if I "treat" that input I lose efficiency.

  • 1

    only do test=v.split() does not resolve ? will convert a space-separated string into a list...

  • try to use map or a list comprehension.

  • It will depend on one thing. Always, will each value be unique? Or can there be keys, like, with a compound name? for example: v = carlos silva 32 years other value

  • What is your true entrance? v = 1 2 3 43 or only 1 2 3 43? If this is the second case, the @ederwander comment solves (by the way, post this as a response). Otherwise, you can first separate the key from the value using x = entrada.split('=') and then separate each individual value using x[1].split().

  • mgibsonbr get 1 2 3 45 65, @ederwander’s comment was very helpful, and I can get to a list, only the list is composed of strings. ['1','2','3','43'], is there a way to turn this list of strings into a list with numbers using some function? I can only imagine trying to convert one by one.

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 an array, using the bounder parameter. The bounder’s default value (which is hidden) is space.

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

Note that it will generate an exception ValueError if not successfully convert.

1

Well come on

There is the possibility of you installing the numpy module ?

Numpy is highly recommended when you start working with vectors and matrix, 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)

0

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.