Python 引用如何工作? [英] How does Python referencing work?

查看:43
本文介绍了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 模块中的 copydeepcopy 来制作对象副本?

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 name d to a dictionary
  • m = d['m'] --> binds the name m to a list
  • m = m[1:] --> binds the name m 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆