gpt4 book ai didi

python - 将切片作为参数传递时会发生什么?

转载 作者:太空宇宙 更新时间:2023-11-03 13:01:02 25 4
gpt4 key购买 nike

我最近遇到了 slice 的问题。检查以下代码:

def clean(l):
for i in range(len(l)):
l[i] = 0

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
clean(lst[:])
print lst

此代码打印出 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

函数内部的l[i] = 0好像没有作用。所以我猜想 Python 在将一个切片传递给函数时正在复制列表……然后我做了另一个测试……

def clean(l):
for i in range(len(l)):
print id(l[i])
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
clean(lst)
print
clean(lst[:])

令我惊讶的是,输出如下:

140373225703016
140373225702992
140373225702968
140373225702944
140373225702920
140373225702896
140373225702872
140373225702848
140373225702824
140373225702800

140373225703016
140373225702992
140373225702968
140373225702944
140373225702920
140373225702896
140373225702872
140373225702848
140373225702824
140373225702800

这表示 Python 不是在复制列表而是在复制引用...这变得很奇怪。既然函数内部的引用还是指向原来的列表对象,为什么设置为0没有效果呢?

最佳答案

切片在应用于列表时返回一个新容器,但内部项目仍然相同。当您将 0 分配给切片列表上的索引时,您正在更改该新容器的值而不是原始列表。

>>> lis = [1, 2, 3]                                           
>>> lis_1 = lis[:]
>>> lis_1 is lis # Outer lists are different
False
>>> lis_1[0] is lis[0]
True
>>> lis_1[0] = 10 # This assignment affects only `lis_1` not `lis`.
>>> lis
[1, 2, 3]
>>> lis_1
[10, 2, 3]
>>>

上面的列表只包含不可变项,当您的列表包含可变项并且您对该项执行就地操作时,所有列表中都可以看到更改:

>>> lis = [[1], 2, 3]
>>> lis_1 = lis[:]
>>> lis_1 is lis #Outer container are different
False
>>> lis[0] is lis_1[0] #But inner lists are same.
True
>>> lis[0].append(10)
>>> lis
[[1, 10], 2, 3]
>>> lis_1
[[1, 10], 2, 3]

来自 docs :

Some objects contain references to other objects; these are called containers. Examples of containers are tuples, lists and dictionaries. The references are part of a container’s value. In most cases, when we talk about the value of a container, we imply the values, not the identities of the contained objects; however, when we talk about the mutability of a container, only the identities of the immediately contained objects are implied. So, if an immutable container (like a tuple) contains a reference to a mutable object, its value changes if that mutable object is changed.

关于python - 将切片作为参数传递时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21210547/

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