Skip to main content
 首页 » 编程设计

python之Python 中的切片列表混淆

2025年05月04日10zhoujg

好吧,我是 Python 的 super 新手,有些关于切片列表的问题困扰着我。当我从此代码中切片 [1] 和 [3] 时,为什么我得到 [1, 3, 4] ?

z = [1, 2, 3, 4, 5] 
del z[1], z[3] 
print z 

我假设我会得到 [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]