【发布时间】:2023-03-28 08:49:01
【问题描述】:
我正在尝试从 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 中从这些数据中得到一个图表
【问题讨论】:
-
你的
csvfile中没有,-delimiter -
最佳猜测
plots=csv.reader(csvfile, delimiter='\t') -
@user3469811 我删除了它,它告诉我这个错误(无法将字符串转换为浮点数)
-
@roganjosh 给了我这个错误无法将字符串转换为浮点数:'0. 1.5'
-
@MohammedALNasrawi 现在应该可以工作了,不是吗?
标签: python