Python 引用如何工作? [英] How does Python referencing work?
本文介绍了Python 引用如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 Python 引用感到困惑.考虑以下示例:
I am confused with Python referencing. Consider the following example:
我的任务:编辑列表中的每个元素
d = { 'm': [1,2,3] }
m = d['m']
m = m[1:] # m changes its reference to the new sliced list, edits m but not d (I wanted to change d)
同样:
d = { 'm': [1,2,3] }
m = d['m']
m = m[0] # As per python referencing, m should be pointing to d['m'] and should have edited d
在python中一切都是通过引用进行的,那么什么时候创建一个新对象?我们是否总是需要 copy
模块中的 copy
和 deepcopy
来制作对象副本?
In python everything goes by reference, then when is a new object created?
Do we always need copy
and deepcopy
from copy
module to make object copies?
请说明.
推荐答案
在 Python 中,变量不是装东西的盒子,而是指向对象的名称.在您的代码中:
In Python a variable is not a box that holds things, it is a name that points to an object. In your code:
d = { 'm': [1,2,3] }
--> 将名称d
绑定到字典m = d['m']
--> 将名称m
绑定到一个列表m = m[1:]
--> 将名称m
绑定到另一个列表
d = { 'm': [1,2,3] }
--> binds the named
to a dictionarym = d['m']
--> binds the namem
to a listm = m[1:]
--> binds the namem
to another list
你的第三行没有改变 m
本身,而是 m
所指向的东西.
Your third line is not changing m
itself, but what m
is pointing to.
要编辑列表中的元素,您可以执行以下操作:
To edit the elements in the list what you can do is:
m = d['m']
for i, item in enumerate(m):
result = do_something_with(item)
m[i] = result
这篇关于Python 引用如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文