简体   繁体   English

使用 for x in y 时出现索引超出范围错误 Python

[英]Index out of range error when using for x in y Python

My code is as follows, and using the for x in y structure to iterate through an array.我的代码如下,并使用 for x in y 结构来遍历数组。

with open('userIDs.csv', 'r', newline='') as csv_file_IDs:
    csv_reader_IDs = csv.reader(csv_file_IDs, delimiter=',')
    for rowID in csv_reader_IDs:
        data = [rowID[0], rowID[1], rowID[2], rowID[3], rowID[4]]
        userIDs.append(data)

However, I'm getting the following error when trying to run my code.但是,尝试运行我的代码时出现以下错误。

in <module>
    data = [rowID[0], rowID[1], rowID[2], rowID[3], rowID[4]]
IndexError: list index out of range

I've checked that there are no blank lines in the CSV file.我检查了 CSV 文件中没有空行。

It's clear that at least one of the lines in your CSV file does not contain the requisite number of values.很明显,CSV 文件中的至少一行不包含必要数量的值。

It would be simpler to do this:这样做会更简单:

import csv
with open('userIDs.csv') as csv_file_IDs:
    userIDs = [e[:5] for e in csv.reader(csv_file_IDs)]
    print(userIDs)

You could then examine the list ( userIDs ) for any elements that don't have enough values然后,您可以检查列表 ( userIDs ) 中没有足够值的任何元素

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

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