列表索引超出范围不明显的原因numpy

时间:2016-05-04 11:40:09

标签: python arrays python-2.7 numpy

我不确定为什么但是我不断收到此错误,即使列表索引不超过索引数。得到此错误的代码如下:

    normalisedFaces = np.array([])
    for f in range(len(vertextNormalIndices)):
        nF1 = vecNormals[vertextNormalIndices[f][0][0]]
        nF2 = vecNormals[vertextNormalIndices[f][1][0]]
        nF3 = vecNormals[vertextNormalIndices[f][2][0]]
        normalisedFaces = np.hstack((normalisedFaces,(np.add(nF1,np.add(nF2,nF3))/ 3)))
        print(f)
    time.sleep(3)
    print(normalisedFaces[f])

我唯一的猜测是我到达了数组最大大小的末尾(?)对于这个例子,循环的范围是529,但是当我达到519时出现错误。如果我将循环更改为:

    for f in range(len(vertextNormalIndices)-200):

然后它到达范围的末尾(所以,在这种情况下:329)。

如何修复此问题?如果可能的话,我不希望不必嵌套这个循环并且必须将每个阵列的大小分成例如%最大== 300

非常感谢任何指导

我在这里附上了错误的屏幕截图: enter image description here

vertexNormalIndices的最后8个索引:(因此,获取每行的第一个数字,例如278,195,281)

enter image description here

1 个答案:

答案 0 :(得分:2)

根据您的评论,并查看您的追溯,错误就在这一行:
nF1 = vecNormals[vertextNormalIndices[f][0][0]]

因此,错误必须vertextNormalIndices[519]vertextNormalIndices[519][0]是一个空列表 - 尝试在循环中打印出来。

暂且不说:

迭代列表的'Pythonic'方法是直接进行,如果你还需要得到每个元素的索引,你应该使用enumerate

normalisedFaces = np.array([])
for f, vertexNormalIndex in enumerate(vertextNormalIndices):
    nF1 = vecNormals[vertextNormalIndex[0][0]]
    nF2 = vecNormals[vertextNormalIndex[1][0]]
    nF3 = vecNormals[vertextNormalIndex[2][0]]
    normalisedFaces = np.hstack((normalisedFaces,(np.add(nF1,np.add(nF2,nF3))/ 3)))
    print(f)
time.sleep(3)
print(normalisedFaces[f])