[英]IndexError: list index out of range when reading text file
我正在尝试从Python中的.txt文件导入数据来绘制它们,当我想运行程序时,我收到此错误:
IndexError:列表索引超出范围
这是一个从文件和数据中绘制一些数据的教程,如下所示:
0.,1.5
2.24425,1.5
4.48276,1.5
5.97701,1.5
7.47126,1.5
8.96552,1.5
11.204,1.5
13.4483,1.5
15.6925,1.5
16.4368,1.5
18.681,1.5
19.4253,1.5
20.75,1.48079
22.3958,1.45845
23.6551,1.42766
24.8608,1.36509
26.1056,1.28529
27.4468,1.21306
28.8132,1.16694
30.1137,1.08216
31.5696,984.851E-03
33.0455,903.886E-03
34.4998,834.626E-03
35.976,790.798E-03
37.5447,754.429E-03
38.9391,697.508E-03
40.6381,715.628E-03
42.5023,882.211E-03
44.4548,1.07169
46.4502,1.26281
47.9939,1.4163
49.4727,1.47307
50.9886 ,1.48932
52.4883,1.49803
53.9846,1.50005
55.4793,1.50108
56.9737,1.50113
58.4647,1.50104
59.9569,1.50067
61.4477,1.50024
62.941,1.49998
64.4312,1.49969
65.9247,1.49929
67.4158,1.49911
68.9096,1.49872
70.4016,1.4976
71.8958,1.49571
73.3918,1.49193
74.8895,1.48612
76.3943,1.4734
77.9068,1.45366
79.4224,1.39481
81.033,1.2964
82.7794,1.1667
84.4811,971.91E-03
86.4866,837.442E-03
88.0979,892.783E-03
89.4046,970.171E-03
90.8885,972.861E-03
92.3106,976.503E-03
93.7562,995.16E-03
95.2745,1.03632
96.7847,1.07072
98.2745,1.10487
99.7581,1.17663
101.079,1.24002
102.408,1.30343
103.686,1.36529
104.979,1.41119
106.239,1.45107
107.577,1.45885
109.25,1.47844
115.057,1.5
116.552,1.5
117.296,1.5
119.54,1.5
121.785,1.5
124.023,1.5
125.517,1.5
126.262,1.5
129.256,1.5
130.,1.5
这是我下面的Python代码,用于导入文件并绘制它:
import matplotlib.pyplot as plt
import csv
x=[]
y=[]
with open('raneen.txt','r') as csvfile:
plots=csv.reader(csvfile, delimiter=',')
for row in plots:
x.append(float(row[0]))
y.append(float(row[1]))
plt.plot(x,y,label='Loaded from file!')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Interesting graph\nCheck it out')
plt.legend()
plt.show()
我希望在Python中使用这个数据的图表
Sicce没有,
在你的数据文件中,你必须在csv.reader
方法中指定delimiter参数:
plots=csv.reader(csvfile, delimiter=' ')
在编辑之前,文件是用可变长度的空格分隔的,就像这样
0. 1.5
2.24425 1.5
4.48276 1.5
5.97701 1.5
7.47126 1.5
8.96552 1.5
11.204 1.5
13.4483 1.5
15.6925 1.5
16.4368 1.5
18.681 1.5
19.4253 1.5
20.75 1.48079
22.3958 1.45845
23.6551 1.42766
24.8608 1.36509
26.1056 1.28529
27.4468 1.21306
28.8132 1.16694
30.1137 1.08216
31.5696 984.851E-03
33.0455 903.886E-03
34.4998 834.626E-03
35.976 790.798E-03
37.5447 754.429E-03
38.9391 697.508E-03
40.6381 715.628E-03
42.5023 882.211E-03
44.4548 1.07169
46.4502 1.26281
47.9939 1.4163
49.4727 1.47307
50.9886 1.48932
因此,为了获得两个向量,您可以这样继续:
x = []
y = []
with open(".../data.txt") as file:
data = file.read()
data = data.split("\n")
for line in data:
line = line.lstrip()
x.append(float(line.split(" ")[0]))
line = line.lstrip(line.split(" ")[0])
y.append(float(line.strip()))
我知道它不是最优雅的方法,它对缺失值敏感,但对于提供的示例,它可以工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.