How to transform a String made up of numbers into a list of integers?

4

I have a list with a string:

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

I want to get every number within that list, turn them into integers, and return the largest and smallest value in that list. I've already tried doing this with FOR IN like this:

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 did not work, and something very strange happened to another list of strings:

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 this list above, which contains four Strings, it worked and I do not know why.

    
asked by anonymous 12.12.2015 / 18:59

3 answers

3

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

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

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

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

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

Calling list transforms the result into a list, allowing it to be used more than once. Then just apply max and min to this list:

>>> x = list(map(int, "10, 20, 30, 40".split(", ")))
>>> [max(x), min(x)]
[40, 10]
    
12.12.2015 / 19:51
3

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

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 yet, to cover the hypotheses of being 'numeric strings' with two or more digits, and if you are sure that it will always be the same pattern in these 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))
    
12.12.2015 / 19:23
1

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

In this case ["1", "2", "3", "4"] your vector has 4 indexes with 4 values, being 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')

At the end you would have to reorder the array by removing the commas imposed by split , and compute 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 have separated the values by commas still outside the quotation marks, there is no need to use split , just scroll through the array using for in and convert to integer using int(i) :

# converter string para inteiro

print type(i) # retorna <str>
print type(int(i)) # retorna <int>
    
12.12.2015 / 19:48