1. 切片操作
>>> c = a[:]
>>> id(a),id(c)
(20249936, 20258128)
2. list()函数
>>> d = list(a)
>>> id(d),id(a)
(20245400, 20249936)
3.
>>> e = a * 1
>>> id(a),id(e)
(20249936, 20250056)
4.
>>> import copy
>>> f = copy.copy(a)
>>> id(a),id(f)
(20249936, 20085496)
5.
>>> import copy
>>> f = copy.deepcopy(a)
>>> id(a),id(f)
(20249936, 20085496)
在python中如果直接对列表等变量使用‘=’的话,只是代表引用,这样的话改变两个对象任意一个值都会相互影响,只相当于起了一个别名而已:
>>> import copy
>>> a = [[10], 20]
>>> b = a[:]
>>> c = list(a)
>>> d = a * 1
>>> e = copy.copy(a)
>>> f = copy.deepcopy(a)
>>> a.append(21)
>>> a[0].append(11)
>>> print id(a), a
30553152 [[10, 11], 20, 21]
>>> print id(b), b
44969816 [[10, 11], 20]
>>> print id(c), c
44855664 [[10, 11], 20]
>>> print id(d), d
44971832 [[10, 11], 20]
>>> print id(e), e
44833088 [[10, 11], 20]
>>> print id(f), f
44834648 [[10], 20]
网友评论