python - Python 中的列表指针

标签 python list pointers

我想澄清一下 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]但声明v=[u,3]存储了初始指针本身而不是变量 u .

对于发生这种情况的原因,这是正确的解释吗?

最佳答案

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

赋值运算符 (=) 用于通过引用将名称绑定(bind)到对象。当您使用名称访问对象时,您将获得对象而不是引用。您无法访问引用的值,也无法像 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 - Python 中的列表指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513657/

相关文章:

python - 如何按\n 拆分嵌套列表但跳过第一个? Python

python - 计算列表中的顺序出现和

c - 复制一个指针,然后返回第一个有什么用

C++ 最大有效内存地址

python - 如何在 python pandas 中标记循环数的值

python - 从向量中有效提取边列表的算法

python - 将类变量传递给类方法

python - pyAudioAnalysis 库错误 : cannot reshape array of size 4400 into shape (220, 10)

list - 可以让 R5RS 代码与 SchemeUnit 一起工作吗?

c - 尝试专门使用内部函数时出现段错误 _mm256_storeu_pd()