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

假装没事ソ 提交于 2021-02-11 15:58:56

问题


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'>. 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?

The first 5 lines of posx_mean_no_acoplo_tf_multiple.txt are:

2.25
2.2695317544146922
2.329339980428795
2.4250625977456477
2.5550797011698574

回答1:


You are nearly there. You just have not assigned the 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.



来源:https://stackoverflow.com/questions/61953188/cannot-convert-list-of-strings-to-list-of-floats-in-python-using-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!