无法使用float()将字符串列表转换为python中的float列表 [英] Cannot convert list of strings to list of floats in python using float()

查看:66
本文介绍了无法使用float()将字符串列表转换为python中的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]

在另一个线程中指定.但是,如果我编写 print(type(contentmediaXoriginal [2])),则输出为< class'str'> .据我所知,我一直在追踪信件的答复.有人可以告诉我为什么我的代码没有将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?

posx_mean_no_acoplo_tf_multiple.txt的前5行是:

The first 5 lines of posx_mean_no_acoplo_tf_multiple.txt are:

2.25
2.2695317544146922
2.329339980428795
2.4250625977456477
2.5550797011698574

推荐答案

您快到了.您只是尚未分配输出.试试这个

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.

这篇关于无法使用float()将字符串列表转换为python中的float列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆