【问题标题】:From string to float python从字符串到浮点 python
【发布时间】:2021-10-09 03:30:36
【问题描述】:

大家好,我还在学习,我想编写一个代码来读取包含来自传感器的数据的文件,所以我一开始就卡住了

    import numpy as np

a = []
b = []
x = []
y = []
for line in open("YAZID.txt", "r"):
    lines = [i for i in line.split()]
    print(lines)
    a.append(float(lines[0]))
    b.append(float(lines[1]))
for i in a:
    i = float(i)
    x.append(i)
print(x)

它给了我这个错误

    ['0,375', '7,84E-02']
Traceback (most recent call last):
  File "c:\Users\pc orange\Desktop\graphs\graph.py", line 32, in <module>
    a.append(float(lines[0]))
ValueError: could not convert string to float: '0,375'

他们被困在字符串中

有没有办法让它们变成浮点数,这样我就可以用它们做一个情节,数字真的很少,我每次都需要读取整个数字

谢谢

【问题讨论】:

  • a.append(float(lines[0].replace(',','.'))
  • @Sujay 我已经回答了here。 :)
  • @Xitiz 哦!这里没有更新

标签: python string floating-point type-conversion valueerror


【解决方案1】:

您可以将 , 替换为 .,然后尝试相同的操作。代码如下:

for line in open("YAZID.txt", "r"):
    lines = [i for i in line.split()]
    print(lines)
    a.append(float(lines[0].replace(",",".")))
    b.append(float(lines[1].replace(",",".")))

这样做应该对你有用。

另外,最后你不必再发float,这样做就可以了。

for i in a:
    x.append(i)
print(x)

【讨论】:

    【解决方案2】:
    string= "3.141"
    
    print(string)
    print(type(string))
    
    # converting string to float
    Float = float(string)
    
    print(Float)
    print(type(Float))
    

    【讨论】:

      【解决方案3】:

      问题出在我的文本文件中,逗号是逗号(,)而不是点(。)也使用此代码将它们变成浮点数

       x = [float(c) for c in a]
      

      感谢大家的帮助

      【讨论】:

      • 但是你的错误在a.append(float(lines[0].replace(",","."))) 所以这在技术上不是一个答案!如果您在添加a 时遵循我的回答,那么您也不必这样做。我在回答中也提到了这一点!我已经回答了你的全部问题,我认为你不必写一个新的答案,你可以接受我的答案,这就是你的问题解决方案!
      • 我在这里很新,所以我仍然不习惯这里的工作方式我使用了你的答案,它完成了工作,谢谢
      猜你喜欢
      • 2012-06-04
      • 2016-06-14
      • 1970-01-01
      • 2016-01-03
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      相关资源
      最近更新 更多