簡體   English   中英

從文件讀取數據時“列表索引超出范圍”

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

任何人都可以幫助解釋為什么此代碼將錯誤顯示為"list index out of range"嗎?

我嘗試用文本文件數據繪制圖形。

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()

文本文件

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

結果

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

正如@Megalng在注釋中指出的那樣,問題出在您的text.txt文件中。 我創建了這個文件:

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

並運行您的代碼以獲取此圖:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM