Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting list of string to list of integer [duplicate]

How do I convert a space separated integer input into a list of integers?

Example input:

list1 = list(input("Enter the unfriendly numbers: "))

Example conversion:

['1', '2', '3', '4', '5']  to  [1, 2, 3, 4, 5]
like image 512
Shriram Avatar asked Apr 27 '12 13:04

Shriram


5 Answers

map() is your friend, it applies the function given as first argument to all items in the list.

map(int, yourlist) 

since it maps every iterable, you can even do:

map(int, input("Enter the unfriendly numbers: "))

which (in python3.x) returns a map object, which can be converted to a list. I assume you are on python3, since you used input, not raw_input.

like image 133
ch3ka Avatar answered Nov 10 '22 14:11

ch3ka


One way is to use list comprehensions:

intlist = [int(x) for x in stringlist]
like image 34
Maehler Avatar answered Nov 10 '22 13:11

Maehler


this works:

nums = [int(x) for x in intstringlist]
like image 3
cobie Avatar answered Nov 10 '22 13:11

cobie


You can try:

x = [int(n) for n in x]
like image 1
Silviu Avatar answered Nov 10 '22 12:11

Silviu


Say there is a list of strings named list_of_strings and output is list of integers named list_of_int. map function is a builtin python function which can be used for this operation.

'''Python 2.7'''
list_of_strings = ['11','12','13']
list_of_int = map(int,list_of_strings)
print list_of_int 
like image 1
Shashank Singh Avatar answered Nov 10 '22 14:11

Shashank Singh