How to transform an array with strings(list) into an integer array in Python?

Asked

Viewed 145 times

2

I’m new to python programming. I came across today the challenge of picking up a vector (ex:V1== ['MESA 11 22 33 44 ']) in which all its elements are in string format (as if they were one, only separated by space). The question is to separate this vector so that it stays in this format: V1==['MESA', 1, 2, 3, 4], where I keep the word MESA as string and the other numbers I convert to integer. I tried it this way: first I tried to turn each string with split() into an index.

for i, vetor in enumerate(V1):
    V1[i].append(vetor[i].split())
print(V1)

After that, I created another vector(V2) to receive the V1 converted to int. Thus, I created an IF so that if at the current position is the word "TABLE", it adds the contents of V1 in V2 without having to convert to int, and if it is different from that, the index will be converted to a number in, int format.

V2=[]
for i in range(len(V1)):
    if V1[i] == 'MESA':
        V2[i]= V1[i]
    else:
        V2[i].append((int(V1[i]))
 print(V2)

I don’t know if my problem is in my logic, but I can’t get the syntax right. I appreciate if anyone can help!

1 answer

4


One Line Solution:

V2=[round(int(k)/11) if k.isdigit() else k for k in V1[0].strip().split(" ")]

I used list comprehension to create the new list. The conditional checks if substring is a digit (is_digit()), if it is not, it leaves the element as it is.

The strip just remove the spaces before and after the string.

Read about list comprehension on documentation. It can help you in similar situations.

  • the result expected by the user is ['MESA', 1, 2, 3, 4]. To achieve this result we must use round(int(k) / 11) instead of int(k).

  • 1

    Thank you @Solkarped . My lack of attention. I will fix

  • Thank you really, helped a lot hehe. I was extremely confused on this, now I understand and I will read the material!

  • Imagine. If this answer solved your problem and there is no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved.

  • Just one more question, if you don’t mind. If the number is negative, for example, would I have to do a function with Try and ecxept so I can convert them? Since isdigit() does not consider the sign "-"

  • 1

    In that case, just replace the probation with k.replace("-","").isdigit()

Show 1 more comment

Browser other questions tagged

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