为什么即使所有索引都有效,也会显示索引超出范围?

Why does this show index out of range even tho all the index are valid?

有人可以向我解释为什么这不起作用吗,这样做时是否存在我没​​有意识到的下划线问题?

a = [1, 2, 3, 4, 5]

i = 0
print(i)
print(a[i] + 3)

print(a)
a[i], a[a[i] + 3] = a[a[i] + 3], a[i] # this shows error even tho below is the same and does not
#a[0], a[4] = a[4], a[0]
print(a)

解包并不是同时发生的。它从左到右解包。

因此,当你解包元组时,你设置了 a[i] = a[a[i] + 3] = 5,然后你尝试设置 a[a[i] + 3] = a[i],但是 a[i] + 3 = 8 超出了范围。

在分配 a[i]= a[a[i] + 3] 之后,列表现在是 [5, 2, 3, 4, 5] 所以,a[a[i] + 3] 变成 a[8],列表中没有。