Converting a list of strings to ints (or doubles)

2019-07-16 15:36发布

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.

3条回答
劳资没心,怎么记你
2楼-- · 2019-07-16 15:52
>>> 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

查看更多
▲ chillily
3楼-- · 2019-07-16 15:52

for Python 3:

listOfStrings = ['4', '-5', '5.763', '6.423', '-5', '-6.77', '10']
listOfFloats = list(map(float, listOfStrings))
查看更多
\"骚年 ilove
4楼-- · 2019-07-16 16:08
>>> [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]
查看更多
登录 后发表回答