You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python新手求助:如何解决IndexError: list index out of range错误?

Fixing the IndexError in Your Python CSV Reading Code

Hey there! Let's break down why you're hitting that IndexError on the hn.append(row[1]) line and get it sorted out.

What's Causing the Error?

The IndexError: list index out of range message tells us that at least one row in your vert.csv file doesn't have enough values. Specifically, when the code tries to grab row[1] (the second value in the row), that row has fewer than 2 elements total. This usually happens for one of these reasons:

  • There's an empty row in your CSV (like a blank line at the end or middle of the file)
  • A row has incomplete data (fewer than 3 columns, maybe a missing comma or value)
  • The CSV uses a delimiter other than commas (like tabs) and the reader isn't parsing it correctly

Step 1: Debug to Find the Problem Row

First, let's modify your code to print every row as it's read—this will show you exactly which row is causing the crash. Update your loop like this:

with open("vert.csv") as csvDataFile:
    csvReader = csv.reader(csvDataFile)
    for idx, row in enumerate(csvReader):
        print(f"Processing row {idx}: {row}")  # Print each row to spot issues
        try:
            lr.append(row[0])
            hn.append(row[1])
            ac.append(row[2])
        except IndexError:
            print(f"⚠️ Skipping invalid row {idx}: Only has {len(row)} columns (needs 3)")

Run this, and you'll see exactly which row is missing data. Empty rows will show up as [], and incomplete rows will have fewer than 3 entries.

Step 2: Fix the Issue

Once you've identified the problem row, you have two straightforward fixes:

  1. Edit the CSV file: Open vert.csv and remove any empty rows, fill in missing values, or make sure all rows use commas as separators.
  2. Keep the error handling: If you can't modify the CSV, leave the try-except block in place to skip bad rows instead of crashing.

Bonus: Use csv.DictReader for Cleaner, Safer Code (If You Have Headers)

If your CSV has a header row (like the first line is LR,HN,Performance), switching to DictReader makes your code more readable and less prone to index errors. Here's how to adjust it:

with open("vert.csv") as csvDataFile:
    # Replace the fieldnames with your actual CSV header labels
    csvReader = csv.DictReader(csvDataFile, fieldnames=["lr", "hn", "ac"])
    next(csvReader)  # Skip the header row if you defined fieldnames manually
    for row in csvReader:
        # Access values by column name instead of index
        lr.append(row["lr"])
        hn.append(row["hn"])
        ac.append(row["ac"])

This way, you don't have to worry about column order, and any missing columns will trigger a clear KeyError instead of a vague index error.

Final Check

After fixing the row issue, your original plotting code should work as expected. Just double-check that your lr, hn, and ac lists are the same length before converting them to numpy arrays!

内容的提问来源于stack exchange,提问作者Courtney Stack

火山引擎 最新活动