gpt4 book ai didi

python - 如果Python切片复制引用,为什么我不能用它来修改原始列表?

转载 作者:行者123 更新时间:2023-12-04 02:36:33 26 4
gpt4 key购买 nike

我知道Slicing lists does not generate copies of the objects in the list; it just copies the references to them.

但如果是这样,那为什么这行不通呢?

l = [1, 2, 3]

# Attempting to modify the element at index 1
l[0:2][-1] = 10

# but the attempt fails. The original list is unchanged
l
> [1, 2, 3]

不应该 l[0:2][-1]指向原始列表索引 1 处的元素?

最佳答案

切片 list返回一个新的浅拷贝 list目的。虽然您没有对原始列表的项目进行深度复制是正确的,但结果是一个全新的 list区别于原版。

Python 3 tutorial :

All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list:

>>> squares = [1, 4, 9, 16, 25]
>>> squares[:]
[1, 4, 9, 16, 25]


考虑
>>> squares[:] is squares
False

关于python - 如果Python切片复制引用,为什么我不能用它来修改原始列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61580214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com