How to transform a string composed of numbers into an integer list?

Asked

Viewed 16,117 times

4

I have a list with a string:

a = ["1, 2, 3, 4"]

I want to take each number inside that list, turn them into integers, and return the highest and lowest value of that list. I’ve tried this with the FOR IN in that way:

def high_and_low(numbers):
    y = []
    for x in numbers:
        if(x == " " or ","):
            continue
        x = int(x)
        y.append(x)
    numbers = y
    mx = max(numbers)
    mn = min(numbers)
    return [mx, mn]

a = ["1, 2, 3, 4"]
print(hl(a))

But it didn’t work, and something very strange happened to another string list:

def high_and_low(numbers):
    y = []
    for x in numbers:
        x = int(x)
        y.append(x)
    numbers = y
    mx = max(numbers)
    mn = min(numbers)
    return [mx, mn]

a = ["1", "2", "3", "4"]
print(hl(a))

With that list up there, which contains four strings, it worked and I don’t know why.

3 answers

2


The reason for this is that a = ["1", "2", "3", "4"] are four strings (four keys each containing a value), of which a[0] = "1", a[1] = "2" etc... In the above example, a = ["1, 2, 3, 4"] you only have a string (a key with a value a[0] = "1, 2, 3, 4").

To do this with example and the logic of the above you can do:

def high_and_low(numbers):
    myNums = []
    for str in numbers: #neste caso a key (str) é uma (0, que a[0] = "1, 2, 3, 4")
        for char in str: #aqui vamos percorrer cada caracter da string ("1, 2, 3, 4")
            try:
                num = int(char)
                myNums.append(num)
            except ValueError as verr:
                pass

    mx = max(myNums)
    mn = min(myNums)
    return [mx, mn]

a = ["1, 2, 3, 4"]
print(high_and_low(a))

or better still, to cover the chances of being 'numeric strings' with two or more digits, and if you are sure it will always be the same pattern in those strings you can:

def high_and_low(numbers):
    myNums = []
    for str in numbers: #neste caso a key (str) é uma (0, que a[0] = "1, 2, 3, 4")   
        splitChars = str.split(", ") # o output é ['1', '2', '3', '4']
        for char in splitChars: #aqui vamos percorrer cada entrada da nossa nova lista, sem os ", "` , e tentar transformar em inteiro
            try:
                num = int(char)
                myNums.append(num)
            except ValueError as verr:
                pass

    mx = max(myNums)
    mn = min(myNums)
    return [mx, mn]

a = ["1, 2, 3, 4"]
print(high_and_low(a))

2

To answer from Miguel already explains the problem and gives a solution proposal, I would just like to propose an alternative solution if your list can contain numbers with more than one digit (ex.: a = ["10, 20, 30, 40"]).

First, you can separate a string into "pieces" using the function split:

>>> "10, 20, 30, 40".split(", ")
['10', '20', '30', '40']

Second, you can apply any function to each element of a list through the built-in map (an understanding of lists would also work, but here the map seems more logical to me):

>>> list(map(int, "10, 20, 30, 40".split(", ")))
[10, 20, 30, 40]

The call to list turns the result into a list, allowing it to be used more than once. Then just apply max and min to that list:

>>> x = list(map(int, "10, 20, 30, 40".split(", ")))
>>> [max(x), min(x)]
[40, 10]

0

It turns out that ["1, 2, 3, 4"] is only a single string, although a being a vector, has only one value, which in this case is this string "1,2,3,4" which acts as a single value.

Already in this case ["1", "2", "3", "4"] your vector has 4 indexes with 4 values, being them 1, 2, 3 and 4.

In the first case you could solve this by separating the values of this string one by one.

#!/usr/bin/python2.7
# -*- coding: utf-8 -*-

a = ['1,2,3,4']
total = []

formato = 'numero {} é inteiro: {}'
for i in a[0].split(','):
    print formato.format(i, 'não' if i.isalnum() == 'true' else 'sim')

In the end you would only have to reorder the array by removing the commas imposed by split, and calculate the maximum and minimum

for x in a[0]:
    if (x == ","):
        continue
    total.append(x)     

print "Maior numero {}".format(max(total))  

print "Menor numero {}".format(min(total))  

In the second case, where you separated the comma values still outside the quotes there is no need to use the split, just go through the array using the for in and convert to whole using the int(i):

# converter string para inteiro

print type(i) # retorna <str>
print type(int(i)) # retorna <int>

Browser other questions tagged

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