gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:23:57 25 4
gpt4 key购买 nike

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

我在列表中的一些列表中有以下数据 --> A

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] 并未超出范围。我希望有人能向我解释为什么我会收到此错误。谢谢

最佳答案

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

>>> 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':

请注意,您可以直接循环列表,不需要生成索引。如果您只是测试,您也不需要使用继续:

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

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

关于python - 收到索引超出范围错误,但我找不到原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38162176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com