收到索引超出范围错误,但我找不到原因?

时间:2016-07-02 16:23:48

标签: python python-2.7 indexoutofrangeexception

我希望有人能帮我解决以下问题:

我在列表的某些列表中有以下数据 - >甲

A = [[['Ghost Block'], ['Ghost Block'], [-7.0, -30000.0, 84935.99999999991, 1.0, 5.0, 0, 84935.99999999991, 1, 1, ['Ghost', 3, 'Ghost', 'Ghost', 'Ghost', 'Ghost', 2, 'Ghost']], [-5.0, -30000.0, 84935.99999999991, 1.0, 4.0, -30000.0, 114935.99999999991, 2, 1, ['Ghost', 3, 'Ghost', 'Ghost', 'Ghost', 'Ghost', 2, 'Ghost']], [-3.0, 33475.49999999997, 84935.99999999991, 1.0, 3.0, -60000.0, 144935.9999999999, 3, 1, ['Ghost', 3, 'Ghost', 'Ghost', 'Ghost', 'Ghost', 2, 'Ghost']], [-1.0, 80158.49999999997, 84935.99999999991, 1.0, 2.0, -26524.50000000003, 111460.49999999994, 4, 1, ['Ghost', 3, 'Ghost', 'Ghost', 'Ghost', 'Ghost', 2, 'Ghost']], [1.0, 31301.99999999997, 84935.99999999991, 1.0, 1.0, 53633.99999999994, 31301.99999999997, 5, 1, ['Ghost', 3, 'Ghost', 'Ghost', 'Ghost', 'Ghost', 2, 'Ghost']]]]
TempValue = 0
Ghost_Block = -60000
for i in range(0,len(A)):
    for item in range(0,len(A[i])):
        if A[i][item] == 'Ghost Block':
            continue
        else:
            if A[i][item][9][0] == 'Ghost': # Neighbor 1
                TempValue += (Ghost_Block*A[i][item][4]) 

我收到以下错误消息:

--> 9             if Value_Spec_Depth[i][item][9][0] == 'Ghost': # Neighbor 1
IndexError: list index out of range

根据我的说法,Value_Spec_Depth [i] [item] [9] [0]不在范围之外。我希望有人可以向我解释为什么我收到这个错误。感谢

1 个答案:

答案 0 :(得分:1)

对于item01A[i][item]['Ghost Block'],而不是'Ghost Block'(请注意1值列表),因此您的if测试永远不会通过,而else块会被执行:

>>> A[0][0]
['Ghost Block']
>>> A[0][1]
['Ghost Block']

因此,else套件尝试访问仅包含一个的列表的索引9。

您可以通过实际测试列表来避免这种情况:

if A[i][item] == ['Ghost Block']:

或测试列表的第一个元素:

if A[i][item][0] == 'Ghost Block':

请注意,您可以直接遍历列表 ,您不需要生成索引。如果您只是测试,您也不需要使用continue

for sublist in A:
    for element in sublist:
        if element[0] != 'Ghost Block' and element[9][0] == 'Ghost':
            TempValue += Ghost_Block * element[4]

另一个改进是使用自定义类而不是列表;根本不清楚每个值的含义是什么。