Question

so I have this code wrote in Python:

def gestionliste():

    liste_usager = input("Veuillez entrer la liste d'entiers:") #this ask the user to enter number(s) of his choice
    liste_usager=liste_usager.split(' ') 
    print(liste_usager)

But for example,if the user enter: 2 3 4, it will result as a string ["2","3","4"]. However,I want to make this list be an integer list like [2,3,4] and not string.How can I do/convert that? I tried that map thing but it didn't work for me.

Thanks a lot!

Was it helpful?

Solution

You can use a list comprehension to convert the numbers into integers:

liste_usager = input("Veuillez entrer la liste d'entiers:")
liste_usager = [int(n) for n in liste_usager.split(' ')]
print(liste_usager)

See a demonstration below:

>>> liste_usager = input(":")
:2 3 4
>>> liste_usager = [int(n) for n in liste_usager.split(' ')]
>>> print(liste_usager)
[2, 3, 4]
>>> print(type(liste_usager[0]))
<class 'int'>
>>>

Edit:

The list comprehension is a one-line solution that is equivalent to doing:

liste_usager = input("Veuillez entrer la liste d'entiers:")

lst = []                           # A list to hold the numbers
for n in liste_usager.split(' '):  # For each item in liste_usager.split(' ')
    n = int(n)                     # Convert it into an integer
    lst.append(n)                  # And add it to lst

liste_usager = lst                 # Reassign liste_usager to lst

print(liste_usager)

OTHER TIPS

Use whitespace (including space character) as a delimiter. This will fail if any of the values the user enters cannot be converted to an integer, such as commas, fractional numbers, and letters.

map(int, liste_usager.split())

You may be better off with:

numbers = []
bad_values = []
for n in liste_usager.split():
    try:
        numbers.append(int(n))
    except ValueError, e:
        bad_values.append(n)
return numbers

You can always use following:

  integers_list=map(int,liste_usager.split())

It will give u a list of integers in form [1,2,3,4] if input is 1 2 3 4 .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top