如果我有一个浮点数,我想把它转换成列表,但它也包含字符串,如何跳过字符串并传递列表中的所有浮点数
如果您只获取列表中的数字
lst = ['NaN','37','45','46','a','32']
lst = [i for i in lst if i.isdigit()]
结果:
['37', '45', '46', '32']
如果您想将上面的列表转换为浮点数
lst = list(map(float, last))
结果:
[37.0, 45.0, 46.0, 32.0]
如果你想用try-except
删除项目,你可以这样做,
In [1]: for item in lst[:]:
...: try:
...: float(item)
...: except TypeError:
...: lst.remove(item)
...:
In [2]: lst
Out[2]: ['37', '45', '46', '32']