Python中的索引超出范围错误(IndexError:列表索引超出范围)

时间:2017-09-29 17:56:02

标签: python python-2.7 indexoutofrangeexception

我似乎无法在这里找到问题,因为我超出了范围问题:

layerZ = [layer_1,layer_2,layer_3,layer_4,layer_5,layer_6,layer_7,layer_8,layer_9,layer_10,layer_11,layer_12,layer_13]
    for x in range(0, 12):
        layerZ_total = [np.size(layerZ[x])]
        layerZ_sp = [np.count_nonzero(layerZ[x]==0)]
        layerZ_nonSp = [np.count_nonzero(layerZ[x])]

        #Printing the results on scree to trace
        print "Layer:",x+1,"Threshhold:",repr(ths),"Total Parameters: ",layerZ_totParam[x],"# Sp: ",layerZ_sp[x],"# Remained : ",layerZ_nonSp[x],"Sp %: ",float(layerZ_sp[x])/layerZ_total[x]

1 个答案:

答案 0 :(得分:1)

这应该有所帮助:

layerZ = [layer_1,layer_2,layer_3,layer_4,layer_5,layer_6,layer_7,layer_8,layer_9,layer_10,layer_11,layer_12,layer_13]

layerZ_total = []
layerZ_sp = []
layerZ_nonSp = []


for x in range(0, 12):
    layerZ_total.append(np.size(layerZ[x]))
    layerZ_sp.append(np.count_nonzero(layerZ[x]==0))
    layerZ_nonSp.append(np.count_nonzero(layerZ[x]))

    #Printing the results on scree to trace
    print "Layer:",x+1,"Threshhold:",repr(ths),"Total Parameters: ",layerZ_total[x],"# Sp: ",layerZ_sp[x],"# Remained : ",layerZ_nonSp[x],"Sp %: ",float(layerZ_sp[x])/layerZ_total[x]

在您的代码中,每次在循环内使用单个值重新初始化列表layerZ_totallayerZ_splayerZ_nonSp,因此在index 0内仅包含一个元素,当您尝试访问某些x index时,会弹出list index out of range错误。

如果您要对layer_*layerZ列表中的每个range(0, 13)进行处理(根据您的要求),您需要x,因为这样做0在值12layer上,从而处理layerZ列表中的每个close