如何将看起来像列表的字符串转换为浮点数列表?

我有这个列表:

s = '[ 0.00889175 -0.04808848  0.06218296 0.06312469 -0.00700571\n -0.08287739]'

它包含一个'\n'字符,我想像这样将其转换为float的列表:

l = [0.00889175,-0.04808848,0.06218296,0.06312469,-0.00700571,-0.08287739]

我尝试了这段代码,与我想要的代码很接近:

l = [x.replace('\n','').strip(' []') for x in s.split(',')]

但它仍然保留我无法删除的引号(我尝试过str.replace("'","")但没有用),这就是我得到的:

['0.00889175 -0.04808848  0.06218296 0.06312469 -0.00700571 -0.08287739']
pypzx 回答:如何将看起来像列表的字符串转换为浮点数列表?

您距离很近。这将起作用:

s = '[ 0.00889175 -0.04808848  0.06218296 0.06312469 -0.00700571\n -0.08287739]'

l = [float(n) for n in s.strip("[]").split()]

print(l)
  

输出:

     
[0.00889175,-0.04808848,0.06218296,0.06312469,-0.00700571,-0.08287739]
,

首先需要清除的是,如果您保留str,那么除非您通过拆分来转换str的每个元素,否则都会有引号。

以下是我对您问题的解决方案:

s='[ 0.00889175 -0.04808848  0.06218296 0.06312469 -0.00700571\n -0.08287739]'

#removing newline \n
new_str = s.replace('\n','')

#stripping the brackets and extra space
new_str = new_str.strip(' []')

#splitting elements into a list
list_of_floats = new_str.split()

#typecasting from str to float
for _i,element in enumerate(list_of_floats):
    list_of_floats[_i] = float(element)

print(list_of_floats)

#output
#[0.00889175,-0.08287739]
本文链接:https://www.f2er.com/3151902.html

大家都在问