简体   繁体   English

Python for loop IndexError:列表索引超出范围

[英]Python for loop IndexError: list index out of range

I am somewhat new to python and I could use some help figuring out what my error entails. 我对python有点陌生,我可以使用一些帮助来弄清楚我的错误需要做什么。

datafile = "filename.csv"

colors = ['Green','White','Yellow','Pink','Blue','Purple','Gray','Brown','Orange','Red','Black']  # put in order of the columns

colnames = []
for color in colors:
    colnames.append(color+"1")
    colnames.append(color+"2")

# Define data structure to hold responses for each column
responses = dict()
for colname in colnames:
    responses[colname] = []

# Read in the responses
lines = open(datafile,"r").readlines()
for line in lines:
    data = line.strip('\n').split(",")
for i,colname in enumerate(colnames):
    if '1' in colname:
        responses[colname].append(data[i])
    else:
        responses[colname].append(data[i].split(','))

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-21-4039ddb1f5f5> in <module>()
     21             responses[colname].append(data[i])
     22         else:
---> 23             responses[colname].append(data[i].split(','))
     24 
     25 # Count the number of subjects

     IndexError: list index out of range

I am not sure if the IndexError: list index out of range is from the actual else: or something is wrong with the responses[colname].append(data[i].split(',')) . 我不确定IndexError: list index out of range实际的else: IndexError: list index out of range else:responses[colname].append(data[i].split(','))出了点问题。 It could also be in my for loop of the list colnames , I am fairly certain that aspect is correct, but you never know 也可能在列表colnames for循环中,我相当确定方面是正确的,但您永远不知道

for line in lines:
    data = line.strip('\n').split(",")

I think the above code is why you got the IndexError ,because the assignment to data will overwrite the previous one, and the content of data is always the last line . 我认为上面的代码就是为什么出现IndexError原因,因为对data的赋值将覆盖前一个,而data的内容始终是最后一行 (Unless you just want the last line). (除非您只想要最后一行)。

eg: 例如:

filename.csv filename.csv

blue,red
red,green
yellow,red

data=['yellow', 'red']

That means your for loop is equivalent to data=lines[-1].strip('\\n').split(",") 这意味着您的for循环等效于data=lines[-1].strip('\\n').split(",")

So I suppose this is what you want: 所以我想这就是你想要的:

data=[]
for line in lines:
    data.append(line.strip('\n').split(","))

Or use this list comprehension: 或使用以下列表理解:

data=[line.strip('\n').split(",") for l in lines]

And then make sure that the length of data is greater than colnames . 然后确保data长度大于colnames By the way, try to debug your code, or print variables, you will find the reason. 顺便说一句,尝试调试代码或print变量,您将找到原因。

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

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