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

你说的曾经没有我的故事 提交于 2019-12-10 22:45:40

问题


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.


回答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




回答2:


>>> [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]



回答3:


for Python 3:

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


来源:https://stackoverflow.com/questions/11722882/converting-a-list-of-strings-to-ints-or-doubles-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!