繁体   English   中英

python:如何解释切片的索引

[英]python: How to interpret indexing of slicing

这是代码:

a = [0, 11, 22, 33, 44, 55]
a[1:4][1] = 666
print(a)

输出为 [0, 11, 22, 33, 44, 55]

所以列表a没有更新,那么那个赋值的效果是什么?

[更新] 感谢@Amadan 的解释,这是有道理的。 但是我还是很疑惑,下面的切片直接更新了列表:

a[1:4] = [111, 222, 333]

直觉上我希望 a[1:4][1] 仍然对列表进行操作,但事实并非如此。

我的直觉错了吗?

a[1:4]创建一个新列表,其元素为[11, 22, 33] 然后用666替换它的 #1 元素,结果是一个列表[11, 666, 33] 然后,因为这个列表没有被任何变量引用,它被遗忘并被垃圾收集。

请注意,如果您有一个 numpy 数组而不是列表,结果会非常不同,因为如果可能,对 numpy 数组进行切片会创建一个视图,而不是一个新数组:

import numpy as np
a = np.array([0, 11, 22, 33, 44])
a[1:4][1] = 666
a
# => array([  0,  11, 666,  33,  44])

这里, a[1:4]不是独立的[11, 22, 33] ,而是原始列表的视图,其中更改a[1:4]实际上更改a

如果您不知道 22 的位置(并想用 666 替换它)或者不关心从列表中删除其他项目,那么这只是另一个需要考虑的解决方案。

a = [0, 11, 22, 33, 44, 55]

# make use of enumerate to keep track of when the item is 22 and replace that 
# with the help of indexing count i.e the position at which 22 is and replace it 
# with 666.

for count,item in enumerate(a):
   if item==22:
      a[count]=666
print(a)

输出:

>>>[0, 11, 666, 33, 44, 55]

希望有帮助,加油!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM