Skip to content Skip to sidebar Skip to footer

Ask A List Of Integer In Python In One Line

def entree_liste(): liste_entier = [] liste_nombre = int(input('Enter list of number separate by space :')) for chiffre in range(liste_nombre): liste_entier.app

Solution 1:

The function int() will convert a single value to integer. But you have one giant string with many integer values embedded in it. To solve this problem, first split the giant string into a collection (in this case, a list) of smaller strings, each containing only one integer and then convert each of those strings separately.

To perform the splitting operation, you can use the Python string method .split(). That will return a list of strings. Each of those strings can then be converted to integer:

 # get list asstring
 list_nombre = input("Enter list of numbers separated by space:")
 # create list of smaller strings, eachwith one integer-as-string
 list_of_int_strings = list_nombre.split(' ') 
 # convert list of strings to list of integers
 list_of_ints = []
 for int_string in list_of_int_strings:
      list_of_ints.append(int(int_string)

However, in Python we would more concisely write:

list_nombre = input("Enter list of numbers separated by space:")

 list_of_ints = ([int(s) for s in list_nombre.split(' ')])

Solution 2:

liste_entier = list(map(int, input("Enter list of number separate by space :").split()))

Solution 3:

As @Larry suggests, this is a reasonable way to write this in Python

list_nombre = input("Enter list of numbers separated by space:")
list_of_ints = [int(s) for s in list_nombre.split()]

The problem is that it's not possible to handle exceptions inside the list comprehension. To do this, you may want to write your own, more robust/helpful conversion function

defconvert_int(s):
    try:
        returnint(s)
    except ValueError as e:
        print e
        returnNone

list_nombre = input("Enter list of numbers separated by space:")
list_of_ints = [convert_int(s) for s in list_nombre.split()]

Solution 4:

What you should do is read in the string, of ints separated by spaces then explode it, and case the entires to int.

input = raw_input("Enter list of number separate by space :")

input.split()

then cast he elements to int

its always safer to read in strings, then deal with the return.

Solution 5:

The int() function will only take a string that contains only digits. Since a space is not a digit, it will cause an error. To fix this problem, first split the string into a list of smaller strings, and then convert each of the smaller strings into an integer if possible.

string = input('Enter list of space separated numbers: ')
 numbers = [int(n) for n in string.split() if n.isdigit()]

Post a Comment for "Ask A List Of Integer In Python In One Line"