Cap*_*cus 1 python list slice del
好吧,我是Python的新手,有些东西让我对切片列表感到烦恼.当我从这段代码中切割[1]和[3]时,为什么我得到[1,3,4]?
z = [1, 2, 3, 4, 5]
del z[1], z[3]
print z
Run Code Online (Sandbox Code Playgroud)
我假设我会[[1,3,5]回来,因为看起来[2]和[4]被删除了.
如果 - > [1,2,3,4,5]
是 - > [0,1,2,3,4]
我的逻辑搞砸了哪里?
第一次删除会更改列表索引,因此下一个删除不是之前的位置...简化
>>> a = [1, 2, 3]
>>> del a[0] # should delete 1
>>> a
[2, 3]
>>> del a[1] # This use to be the index for 2, but now `3` is at this index
>>> a
[2]
Run Code Online (Sandbox Code Playgroud)