简体   繁体   English

从文件读取数据时“列表索引超出范围”

[英]“list index out of range” when reading data from file

Anyone help to explain why this code gives the error as "list index out of range" ? 任何人都可以帮助解释为什么此代码将错误显示为"list index out of range"吗?

I've tried on drawing a graph with text file data. 我尝试用文本文件数据绘制图形。

import matplotlib.pyplot as plt
import csv
x,y = [],[]
with open('text.txt','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for row in plots:
        x.append(int(row[0]))
        y.append(int(row[1]))
plt.legend()
plt.show()

Text file 文本文件

0, 1
1, 3
2, 7
3, 5
....

Result 结果

IndexError                             Traceback (most recent call last)
<ipython-input-5-f3977bc887cc> in <module>()
      5     plots = csv.reader(csvfile, delimiter=',')
      6     for row in plots:
----> 7         x.append(int(row[0]))
      8         y.append(int(row[1]))
      9     plt.legend()

IndexError: list index out of range

As @Megalng pointed out in the comments, the problem is in your text.txt file. 正如@Megalng在注释中指出的那样,问题出在您的text.txt文件中。 I created this file : 我创建了这个文件:

12, 12
13, 12
14, 12
15, 13
16, 14
17, 14
18, 15
19, 15
20, 15

and ran your code to get this graph : 并运行您的代码以获取此图:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM