python数组中数据位置交换 -- IndexError: list assignment index out of range

代码:

t = [-10,-3,-100,-1000,-239,1]
# 交换 -10和1的位置
t[5], t[t[5]-1] = t[t[5]-1], t[5]

报错:

 IndexError: list assignment index out of range

数组:

>>> t
[-10,-3,-100,-1000,-239,-10]

为什么?

等式右边 t[t[5]-1] 相当于 t[0] ,是对值-10的引用.首先是将t[5]的引用指向-10,此时 t[5] 的值变为-10,左边 t[t[5]-1] 相当于变成 t[-11] 

猜你喜欢

转载自www.cnblogs.com/chimpan/p/9705818.html