简体   繁体   English

无法使用 float() 将字符串列表转换为 python 中的浮点列表

[英]Cannot convert list of strings to list of floats in python using float()

I am trying to change the elements of a list of strings to floats using the method defined in this thread .我正在尝试使用此线程中定义的方法将字符串列表的元素更改为浮点数。 I write我写的

with open('posx_mean_no_acoplo_tf_multiple.txt', 'r') as fmediaXoriginal:
    contentmediaXoriginal = fmediaXoriginal.readlines()
    contentmediaXoriginal = [x.strip() for x in contentmediaXoriginal] 
    [float(i) for i in contentmediaXoriginal]

As specified in the other thread.如另一个线程中所述。 However, if I write print(type(contentmediaXoriginal[2])) , then, the output is <class 'str'> .但是,如果我写print(type(contentmediaXoriginal[2])) ,那么 output 是<class 'str'> As far as I can see, I am following the accepted answer to the letter.据我所知,我正在遵循对这封信的接受答复。 Can someone tell me why my code is not converting the elements of contentmediaXoriginal to floats?有人能告诉我为什么我的代码没有将 contentmediaXoriginal 的元素转换为浮点数吗?

The first 5 lines of posx_mean_no_acoplo_tf_multiple.txt are: posx_mean_no_acoplo_tf_multiple.txt 的前 5 行是:

2.25
2.2695317544146922
2.329339980428795
2.4250625977456477
2.5550797011698574

You are nearly there.你快到了。 You just have not assigned the output.您只是没有分配 output。 Try this尝试这个

with open('posx_mean_no_acoplo_tf_multiple.txt', 'r') as fmediaXoriginal:
contentmediaXoriginal = fmediaXoriginal.readlines()
contentmediaXoriginal = [float(x.strip()) for x in contentmediaXoriginal] 

Note: Please fix indentation as you require it.注意:请根据需要修复缩进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM