簡體   English   中英

如何解決 IndexError: list index out of range?

[英]How to resolve IndexError: list index out of range?

我是 python 的新手,我正在嘗試為單元做一個分配,但我似乎無法克服索引錯誤。 我已經嘗試了所有我能想到的以及我可以在互聯網上找到的任何東西,但我無法弄清楚出了什么問題。

這是我試圖開始工作的代碼。

兩個文件都在同一個文件夾中。

錯誤消息不斷出現在“hn.append(row[1])”上

import numpy as np    
import csv           
#import the ploting library bits
from mpl_toolkits.mplot3d import Axes3D   # for our 3-D plots
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

lr = []    
hn = []
ac = []

with open("vert.csv") as csvDataFile:   
    csvReader = csv.reader(csvDataFile)  
    for row in csvReader:
        lr.append(row[0])
        hn.append(row[1])
        ac.append(row[2])

x = np.asfarray(lr[1:])
y = np.asfarray(hn[1:])
z = np.asfarray(ac[1:])*100   

ax.scatter(x, y, z, c='r', marker='o')    # plot the x,y,z, data points

ax.set_ylabel('LR')    # axis labels
ax.set_xlabel('NH')
ax.set_zlabel('Performance')

plt.show()

這是完整的錯誤消息

        IndexError                                
        Traceback (most recent call last) <ipython-input-35-0752ace9229f> in <module>
        19     for row in csvReader:
        20         lr.append(row[0])
        ---> 21         hn.append(row[1])
        22         ac.append(row[2])
        23 

        IndexError: list index out of range

因為您已經通過確保 CSV 文件中至少有 3 列解決了IndexError問題,以克服ValueError ,將lrhnac轉換為浮點數。 它們目前是字符串,而您的繪圖需要浮點數或整數:

lr1 = [float(x) for x in lr] #create a list lr1 with same elements as lr but elements type is float, using list comprehension
hn1 = [float(y) for y in hn] # same operation for hn
ac1 = [float(x) for x in ac] # same operation for ac
x = np.asfarray(lr1[1:])
y = np.asfarray(hn1[1:])
z = np.asfarray(ac1[1:])*100  

暫無
暫無

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

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