跳过文件中的字符串并在列表中附加浮点数

To skip the strings from a file and append floating numbers in list

提问人:Prachi 提问时间:10/14/2022 更新时间:10/15/2022 访问量:23

问:

如果我有一个浮点数,我想将其转换为列表,但它也包含字符串,如何跳过字符串并传递列表中的所有浮点数

字符串 列表 浮点数

评论

0赞 Rahul K P 10/14/2022
请提供一些示例输入和输出。你也没有提到编程语言。
0赞 Prachi 10/15/2022
list = ['NaN','37','45','46','a','32'] list2 = [] try: for item in list: if item == 'NaN': list.remove(item) continue elif item == 'a': list.remove(item) continue list = [float(item) for item in list] print(list) except ValueError: print(“跳过第 18 行:无法将字符串转换为浮点数:'a'”)
0赞 Rahul K P 10/15/2022
列表中的怎么样?a
0赞 Prachi 10/15/2022
我想使用 try 和 except 跳过字符串。例如,如果一个字符串是“a”,那么使用 try 和 except 我必须显示 print(“跳过第 18 行:无法将字符串转换为浮点数:'a'”),如果它是 NaN,我想跳过该字符串。我尝试了很多东西,但都做不到
0赞 Rahul K P 10/15/2022
发布在回答环节。

答:

0赞 Rahul K P 10/15/2022 #1

如果您只获取列表中的数字

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