== 和 is
is 是比较两个引用是否指向了同一个对象(引用比较)。
== 是比较两个对象是否相等。
In [1]: a = [1,2,3]
In [2]: b = a
In [3]: a == b
Out[3]: True
In [4]: a is b
Out[4]: True
In [5]: import copy
In [6]: c = copy.deepcopy(a)
In [7]: a == c
Out[7]: True
In [8]: a is c
Out[8]: False
浅拷贝
浅拷贝是对一个对象的顶层拷贝
通俗的理解就是:拷贝了引用,并没有拷贝内容
In [1]: a = [1,2,3]
In [2]: id(a)
Out[2]: 139650508626376
In [3]: b = a
In [4]: id(b)
Out[4]: 139650508626376
In [5]: a.append(4)
In [6]: a
Out[6]: [1, 2, 3, 4]
In [7]: b
Out[7]: [1, 2, 3, 4]
In [8]: a = {'name':'二哈'}
In [9]: id(a)
Out[9]: 139650508722376
In [10]: id(b)
Out[10]: 139650508626376
In [10]: id(b)
Out[10]: 139650508626376
In [11]: a['ID'] = 100
In [12]: a
Out[12]: {'ID': 100, 'name': '二哈'}
In [13]: b
Out[13]: [1, 2, 3, 4]
In [14]: b = a
In [15]: b
Out[15]: {'ID': 100, 'name': '二哈'}
In [16]: id(a)
Out[16]: 139650508722376
In [17]: id(b)
Out[17]: 139650508722376
In [18]:
深拷贝
深拷贝是对于一个对象所有层次的拷贝(递归)
In [1]: import copy
In [2]: a = [1,2,3]
In [3]: id(a)
Out[3]: 140269250702600
In [4]: b = copy.deepcopy(a)
In [5]: id(b)
Out[5]: 140269250690120
In [6]: a
Out[6]: [1, 2, 3]
In [7]: b
Out[7]: [1, 2, 3]
In [8]: a.append(4)
In [9]: a
Out[9]: [1, 2, 3, 4]
In [10]: b
Out[10]: [1, 2, 3]
列表推倒式
所谓的列表推导式,就是指的轻量级循环创建列表
n [12]: a = [(x,y,z) for x in range(0,2) for y in range(0,2) for z in range(0,
...: 2)]
In [13]: a
Out[13]:
[(0, 0, 0),
(0, 0, 1),
(0, 1, 0),
(0, 1, 1),
(1, 0, 0),
(1, 0, 1),
(1, 1, 0),
(1, 1, 1)]