【问题标题】:List Pointer in Python [duplicate]Python中的列表指针[重复]
【发布时间】:2020-04-18 04:27:39
【问题描述】:

我想澄清一下 Python 中的一个简单指针机制。考虑以下几点:

u = [1,2]
v = [u,3]
print(v)
u[0] = 100
print(v)

那么结果就是

[[1,2],3]
[[100,2],3]

同时如果我们执行

u = [1,2]
v = [u,3]
print(v)
u = [100,2]
print(v)

那么结果就是

[[1,2],3]
[[1,2],3]

我认为这是因为在第一个代码中,u 存储的指针始终没有改变,而在第二个代码中,u 存储的指针从声明 u=[100,2] 更改,但声明 @987654333 @ 存储了初始指针本身,而不是变量 u

这是为什么发生这种情况的正确解释吗?

【问题讨论】:

  • 当然。要为第二个数组获得相同的行为,您必须执行 u[:] = [100, 2]。
  • Ned Batchelder 文章的必填链接:nedbatchelder.com/text/names.html
  • 第二个例子中的赋值使得u指向一个不同的对象,所以对u的操作不再影响v中的对象。 -nedbatchelder.com/text/names.html。 …docs.python.org/3/reference/…docs.python.org/3/reference/….
  • 如果您在 Python Visualizer 工具中运行这两个示例,您将很容易理解发生了什么pythontutor.com/visualize.html#mode=edit
  • Python 容器保存对对象的引用。一切都是对象。值是一个对象。名称是一个引用(任何一个术语都比术语变量更可取,后者会调用一个存储值的框,因为这不适用于 Python)。您将名称绑定到对象,或就地更改对象。将名称重新绑定到另一个对象不会影响原始对象,除非不再引用它。

标签: python list pointers


【解决方案1】:

Python 没有指针的概念,根据指针来考虑 Python 结构可能会产生误导。 Python 有对象的名称和引用,而不是指针(Python 中的一切都是对象)。

赋值运算符 (=) 用于将名称绑定到具有引用的对象。当您使用其名称访问对象时,您将获得对象而不是引用。您无法访问引用的值,也无法像 C 中的指针运算那样操作引用。考虑到这一点,让我用 Python 术语分解您的代码:

# A new list object is created and bound to the name `u`. 
# It only has `int` elements which are immutable
u = [1,2]
# A different list object is created and bound to the name `v`.
# Its first element is an other list object which is bound to the name `u` at this point. 
v = [u,3]
print(v)
# __setitem__(0, 100) is called on the list object under the name `u`
# The first element of `v` remains this altered object.
u[0] = 100
print(v)

# Same as before
u = [1,2]
v = [u,3]
print(v)
# A new list object is created and bound to the name `u`.
# The previous list object bound to `u` remains the first element of `v` which is unchanged.
u = [100,2]
print(v)

希望对你有帮助

【讨论】:

  • 好的,谢谢! Python没有指针!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
  • 1970-01-01
  • 2010-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多