Python:通过引用和切片分配传递 [英] Python: Pass by reference and slice assignment
本文介绍了Python:通过引用和切片分配传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,列表通过引用传递给函数,对吧?
In Python, lists are passed by reference to functions, right?
如果是这样,那么发生了什么?
If that is so, what's happening here?
>>> def f(a):
... print(a)
... a = a[:2]
... print(a)
...
>>> b = [1,2,3]
>>> f(b)
[1, 2, 3]
[1, 2]
>>> print(b)
[1, 2, 3]
>>>
推荐答案
事实上,对象是通过引用传递的,但 a = a [:2]
基本上创建一个新的局部变量,指向列表的切片。
Indeed the objects are passed by reference but a = a[:2]
basically creates a new local variable that points to slice of the list.
修改列表对象到位后,您可以将其分配给其切片(切片分配)。
To modify the list object in place you can assign it to its slice(slice assignment).
考虑 a
和 b
在这里相当于你的全局 b
和本地 a
,这里赋值 a
不会影响 b
:
Consider a
and b
here equivalent to your global b
and local a
, here assigning a
to new object doesn't affect b
:
>>> a = b = [1, 2, 3]
>>> a = a[:2] # The identifier `a` now points to a new object, nothing changes for `b`.
>>> a, b
([1, 2], [1, 2, 3])
>>> id(a), id(b)
(4370921480, 4369473992) # `a` now points to a different object
切片分配按预期工作:
Slice assignment work as expected:
>>> a = b = [1, 2, 3]
>>> a[:] = a[:2] # Updates the object in-place, hence affects all references.
>>> a, b
([1, 2], [1, 2])
>>> id(a), id(b)
(4370940488, 4370940488) # Both still point to the same object
这篇关于Python:通过引用和切片分配传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文