Converting a list of strings to ints (or doubles) in Python

30,428

Solution 1

>>> lst = ['4', '-5', '5.763', '6.423', '-5', '-6.77', '10']
>>> map(float, lst)
[4.0, -5.0, 5.763, 6.423, -5.0, -6.77, 10.0]

And don't use list as a variable name

Solution 2

for Python 3:

listOfStrings = ['4', '-5', '5.763', '6.423', '-5', '-6.77', '10']
listOfFloats = list(map(float, listOfStrings))

Solution 3

>>> [float(x) for x in ['4', '-5', '5.763', '6.423', '-5', '-6.77', '10']]
[4.0, -5.0, 5.763, 6.423, -5.0, -6.77, 10.0]
Share:
30,428
user1532369
Author by

user1532369

Updated on July 09, 2022

Comments

  • user1532369
    user1532369 almost 2 years

    I have a lots of list of strings that look similar to this:

    list = ['4', '-5', '5.763', '6.423', '-5', '-6.77', '10']
    

    I want to convert it to a list of ints (or doubles) but the - keeps producing an error.