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

时间:2017-03-28 18:16:28

标签: python jupyter-notebook

我对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

我不确定IndexError: list index out of range是否来自实际else:responses[colname].append(data[i].split(','))是否有问题。 它也可以在列表for的{​​{1}}循环中,我相当确定方面是正确的,但你永远不会知道

1 个答案:

答案 0 :(得分:0)

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

我认为以上代码是您获得IndexError的原因,因为data的分配将覆盖之前的代码,而data的内容始终是线即可。 (除非你只想要最后一行)。

e.g:

<强> filename.csv

blue,red
red,green
yellow,red
data=['yellow', 'red']

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

所以我想这就是你想要的:

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

或使用此列表理解:

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

然后确保data的长度大于colnames。 顺便说一下,尝试调试代码或print变量,你会发现原因。

相关问题