【问题标题】:saving data from two columns into two lists将两列中的数据保存到两个列表中
【发布时间】:2020-11-08 21:15:02
【问题描述】:

我有两列浮点数。我需要将每列中的数据分成单独的列表(x 和 y)并绘制数据 y 与 x。我写了一些东西,但它一直给我一个错误,那就是, ValueError: 需要超过 1 个值才能解压

数据文件的提取如下,

0.0 1.0   
0.02 1.0   
0.04 1.0  
0.06 1.0  
0.08 1.0   
0.1 1.0   
0.12 1.0   
0.14 1.0   
0.16 1.0   
0.18 1.0   
0.2 1.0  
0.22 1.0   
0.24 1.0   
0.26 1.0   
0.28 1.0   
0.3 1.0  

我的代码看起来像这样,

  import NumPy as np
  import math

  f = open('partA-imag.dat' , "r").  
  lines = f.readlines(). 
  #file.close().                                                                       
  x_axis = [].                                                                       
  y_axis = [].                                                                       
  for line in lines: 
      x,y = line.split(). 
      x_axis.append(x). 
      y_axis.append(y). 
      print(x,y). 

  print(x_axis). 
  print(y_axis). 
  plt.plot(x_axis,y_axis). 
  plt.show()

【问题讨论】:

  • 试试lines = f.read()
  • 不,没用
  • 你能准确地显示文件中的数据是什么样的吗?试试x, y = line.split(' ')
  • 这仍然给我同样的错误。
  • 我更新了提取的数据,使其更加清晰。此处提取的数据是从顶部到某个点,所有其他行看起来完全相同。

标签: python list numpy math split


【解决方案1】:
lines = f.readlines()
x_ = []
y_ = []
for line in lines:
    x, y = line.split(' ')
    x_.append(float(x.rstrip()))
    y_.append(float(y.rstrip()))

【讨论】:

  • 给了我这个错误“y_.append(float(y.rstrip()))。ValueError: could not convert string to float:”
  • 这意味着一个空行来了,检查空行
  • 老实说,两列中都没有空行
  • 我希望有一种方法可以将数据文件分享给您,以便您也可以看到它!
  • @Xdrake 我设法通过更改此行 x, y = line.split() 对您的文件执行此操作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-31
  • 1970-01-01
相关资源
最近更新 更多