作业规则

mic*_*yer 5 python python-3.x

我注意到了一个(看似)奇怪的分配行为,这让我多次犯了编程错误.

首先参见以下示例:

>>> 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在递增时才显式引用.

我有两个问题:

  1. 为什么会这样?
  2. 我应该注意哪些特殊规则吗?

Ash*_*ary 8

那是因为整数是不可变的,列表是可变的.

>>> 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)