python3随笔-copy与索引

>>> import copy
>>> x=[1,2,3]
>>> z=copy.copy(x)
>>> x
[1, 2, 3]
>>> z
[1, 2, 3]
>>> y=copy.deepcopy(x)
>>> y
[1, 2, 3]
>>> z
[1, 2, 3]

列表直接赋值采用的是复制其引用,而不是值复制,而调用copy模块则实现真正的复制。

>>> y[1]=12
>>> z[0]=31
>>> x
[1, 2, 3]
>>> y
[1, 12, 3]
>>> z
[31, 2, 3]

copy和deepcopy都实现了数据的复制,但其实不然。
copy为浅copy,只复制了第一层数据,列表里存储的子列表,打印出来是子列表,其实,在内存里,列表里只是存储了子列表的内存地址,子列表在内存里是单独存储的
比如:

>>> x
[11, 23, [16, 11, 15]]
>>> z=copy.copy(x)
>>> x
[11, 23, [16, 11, 15]]
>>> z
[11, 23, [16, 11, 15]]
>>> z[0]=9
>>>
>>> z
[9, 23, [16, 11, 15]]
>>> x
[11, 23, [16, 11, 15]]
>>> z[2][0]=222
>>> z
[9, 23, [222, 11, 15]]
>>> x
[11, 23, [222, 11, 15]]

下面代码没有改变x的原因是因为z在第一层实现的复制,只是简单把第1层的第3个元素进行了替代。

>>> z[2]=[101,102,103]
>>> z
[9, 23, [101, 102, 103]]
>>> x
[11, 23, [222, 11, 15]]
>>>

deepcopy实现了完全复制

>>> x
[11, 23, [222, 11, 15]]
>>> y=copy.deepcopy(x)
>>> x
[11, 23, [222, 11, 15]]
>>> y
[11, 23, [222, 11, 15]]
>>> y[2][1]=10001
>>> y
[11, 23, [222, 10001, 15]]
>>> x
[11, 23, [222, 11, 15]]
>>>
正

向索引与负向索引

>>> x=[1,2,3,4,5,6]
>>> x[-1]
6
>>> x[-2]
5
>>> x[1]
2
>>> x[0]
1

你可能感兴趣的:(AI)