繁体   English   中英

python 如何在列表和整数中存储东西?

[英]How does python store things in lists vs integers?

如果我执行以下操作:

v = [0,0,0,0]
v2 = v
v[0]=5
print(v2)

对列表 v 的更改更改了列表 v2。

a=5
b=a
a=6
print(b)

另一方面,如果我这样做,则更改 a 不会更改 b。 这里有什么区别? 当我打印 id(a) 和 id(b) 时,它们给出相同的数字,所以它们不应该引用相同的 object 并像列表一样进行更改吗?

您最初的问题实际上是在询问两个不同的事情。

第一个是这个,带有一些注释 - 你询问列表。 列表是可变序列的对象,在您的代码中, vv2始终引用同一个列表。 您可以使用任何引用它的列表来修改列表的内容,并且这些更改对引用它的任何内容都是可见的。

v = [0,0,0,0] # create a list object and assign reference to v

v2 = v        # assign v2 to be the reference to list v also refers to

v[0]=5        # modify first list element

print(v2)     # print the list v2 refers to, which is the same list v refers to

在您展示的第二段代码中,您正在更改变量所指的内容,而不是更改 object 的基础值。

a=5      # Assign a to be a reference to 5

b=a      # Assign b to be a reference to the thing a refers to

a=6      # Re-assign a to refer to 6, a now refers to a different object than b

print(b) # b still refers to 5

你指出了id的使用。 我还将介绍sys.getrefcount() ,它可以让您查看任何特定 object 的引用计数是多少,因此我们可以看到,例如v的引用列表有多个引用它的东西。

import sys

v = [0,0,0,0] 

v2 = v        

v[0]=5        

print(f"id(v) = {id(v)}")
print(f"id(v2) = {id(v2)}")

# this shows 3 instead of 2 because getrefcount(x)
# increases refcount of x by 1
print(f"v referrers: {sys.getrefcount(v)}")

del v2 # remove v2 as a reference

# and this will show 2 because v2 doesn't
# exist/doesn't refer to it anymore
print(f"v referrers: {sys.getrefcount(v)}")

a = 5
b = 5
print(f"id(a) = {id(a)}")
print(f"id(b) = {id(b)}")

# you're reassigning a here, so the id will change
# but you didn't change what b refers to
a = 6
print(f"id(a) = {id(a)}")
print(f"id(b) = {id(b)}")

而这个的 output 看起来像这样......

id(v) = 4366332480
id(v2) = 4366332480
v referrers: 3
v referrers: 2

id(a) = 4365582704
id(b) = 4365582704
id(a) = 4365582736
id(b) = 4365582704

And as I mentioned - CPython does some special stuff for numbers in the range of [-5, 256] and keeps a static list of them in memory, so id on any integer in that range should return the same value for any referrers to them .

是的,它是 python 列表概念。 如果您不想更改值,请使用复制方法:

list_1 = [0,0,0,0]
list_2 = list_1.copy()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM