【问题标题】:How to resolve IndexError: list index out of range?如何解决 IndexError:列表索引超出范围?
【发布时间】:2020-09-09 10:33:37
【问题描述】:

我是 python 新手,我正在尝试为 unit 分配,但我似乎无法克服索引错误。我已经尝试了所有我能想到的以及我在互联网上可以找到的所有内容,但我无法找出问题所在。

这是我要开始工作的代码。

两个文件都在同一个文件夹中。

错误消息不断出现在“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 阅读器的阅读量比您想象的要少,row 变量仅对索引 0 有效,而不再对 1 有效。
  • 检查 csv 文件是否至少有 3 列
  • 感谢您的帮助!我的文件中有 4 列,但现在我将索引更改为 0 我得到一个 ValueError: could not convert string to float: ' "cells": ['
  • 我会在for row in csvReader: 之后添加一个print(row)。这样我就对读者给我的东西有一个清晰的(呃)想法。它真的是一个至少包含 3 个元素的列表吗?这些元素是字符串还是数字?

标签: python numpy matplotlib


【解决方案1】:

由于您已通过确保 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  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多