我注意到了一个(看似)奇怪的分配行为,这让我多次犯了编程错误.
首先参见以下示例:
>>> i = 0
>>> t = (i,)
>>> t
(0,)
>>> i += 1
>>> t
(0,)
Run Code Online (Sandbox Code Playgroud)
正如所料,t
即使在增加值之后,唯一元素的值也不会改变i
.
现在看到以下内容:
>>> l = [0]
>>> t = (l,)
>>> t
([0],)
>>> l[0] += 1
>>> t
([1],) # <- ?
Run Code Online (Sandbox Code Playgroud)
我不明白为什么最初的零t
现在是一个; 如果我通过引用增加它t
...
>>> t[0][0] += 1
Run Code Online (Sandbox Code Playgroud)
...我知道它的值已经改变了,但在前面的例子中并非如此,其中只有l
在递增时才显式引用.
我有两个问题:
那是因为整数是不可变的,列表是可变的.
>>> i = 0
>>> t = (i,)
>>> t[0] is i # both of them point to the same immutable object
True
>>> i += 1 # We can't modify an immutable object, changing `i` simply
# makes it point to a new object 2.
# All other references to the original object(0) are still intact.
>>> i
1
>>> t # t still points to the same 0
(0,)
>>> x = y = 1
>>> id(x),id(y)
(137793280, 137793280)
>>> x += 1
>>> id(x),id(y) #y still points to the same object
(137793296, 137793280)
Run Code Online (Sandbox Code Playgroud)
列表:
>>> l = [0]
>>> t = (l,)
>>> t[0] is l #both t[0] and l point to the same object [0]
True
>>> l[0] += 1 # modify [0] in-place
>>> t
([1],)
>>> l
[1]
#another exmple
>>> x = y =[] # x, y point to the same object
>>> x.append(1) # list.append modifies the list in-place
>>> x, y
([1], [1])
>>> x = x + [2] # only changes x, x now points to a new object
>>> x, y
([1, 2], [1])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
255 次 |
最近记录: |