赋值建立对象引用值,而不是建立对象的拷贝。
序号 | 代表语句 | 类型 |
---|---|---|
1 | a=1 |
基本语句 |
2 | a=b |
共享b的引用 |
3 | [a,b]=[1,2] |
列表赋值 |
4 | a,b=[1,2] |
序列赋值 |
5 | a,b=1,2 |
序列赋值相当于(1,2) |
6 | a,*b=1,2,3 |
扩展的序列赋值 |
7 | [a,[b,c]]=[1,[2,3]] |
嵌套赋值 |
8 | a=b=1 |
多目标赋值 |
9 | a+=1 |
增强赋值 |
【注】:式中的[]可替换为()或{},[1,2]可替换为长度为2的字符串。
a=b,使得a,b共享对象[1,2]的引用,当b进行修改时,a会发生改变。
In [1]: b=[1,2]
In [2]: a=b
In [3]: a
Out[3]: [1, 2]
In [4]: b.append(3)
In [5]: b
Out[5]: [1, 2, 3]
In [6]: a
Out[6]: [1, 2, 3]
要避免修改,可以采取两种方式。
In [7]: b=[1,2]
In [8]: a=b.copy() #或者 a=b[:]
In [9]: b.append(3)
In [10]: b
Out[10]: [1, 2, 3]
In [11]: a
Out[11]: [1, 2]
对象个数要相同,否则报错,列表可换成元组,支持嵌套赋值,见6。
代表语句 |
---|
[a,b]="st" |
[a,b]=[1,2] |
[a,b]=range(2) |
[a,b]=1,2 |
代表语句 |
---|
a,b="st" |
a,b=[1,2] |
a,b=list(range(2)) |
a,b=1,2 |
In [1]: a,*b="abc"
In [2]: print(a,b)
a ['b', 'c']
In [3]: a,*b="ab"
In [4]: print(a,b)
a ['b']
In [5]: a,*b="a"
In [6]: print(a,b)
a []
In [7]: a,b,*c="abcd"
In [8]: print(a,b,c)
a b ['c', 'd']
In [9]: a,*b,c="abcd"
In [10]: print(a,b,c)
a ['b', 'c'] d
In [11]: *a,b,c="abcd"
In [12]: print(a,b,c)
['a', 'b'] c d
{}、[]、()可混用
代表语句 |
---|
[a,[b,c]]="stm" |
[a,(b,c)]=[1,[1,2]] |
[a,(b,c)]=1,[2,3] #若为1,2,3报错 |
for [a,b] in [[1,2],[3,4]] |
for [a,[b,c]] in [[1,[2,3]],[3,[4,5]]] |
a=b时,a是b的引用,b修改a自然修改
In [1]: a=b=1
In [2]: b=2
In [3]: a
Out[3]: 1
In [4]: a=b=[1,2]
In [5]: b.append(3) #b=[1,2,3]
In [6]: a
Out[6]: [1, 2, 3]
a,b所引用的对象不一样,虽然对象的值是一样的
In [7]: a=[1,2]
In [8]: b=[1,2]
In [9]: b.append(3)
In [10]: b
Out[10]: [1, 2, 3]
In [11]: a
Out[11]: [1, 2]
如下代码可区分两者,==只判断值,不判断引用对象类型
In [12]: a=b=[1,2]
In [13]: a==b
Out[13]: True
In [14]: a is b
Out[14]: True
In [15]: a=[1,2]
In [16]: b=[1,2]
In [17]: a==b
Out[17]: True
In [18]: a is b
Out[18]: False
In [1]: a=[1,2]
In [2]: b=a
In [3]: a=a+[3,4] #创建了新对象
In [4]: a,b
Out[4]: ([1, 2, 3, 4], [1, 2])
In [5]: a=[1,2]
In [6]: b=a
In [7]: a+=[3,4] #在原处修改,b是a的引用,导致b也改变
In [8]: a,b
Out[8]: ([1, 2, 3, 4], [1, 2, 3, 4])