首先感谢,资料由网上的查询共享并保存下来的,该资料完全是用来学习,希望大家有用。
1.在列表中存在一个名为copy的方法,就像字面意思一样copy方法是用于复制列表元素的,示例如下:
1 names = [‘Zhangsan’,’Lisi’,’WangErgou’]2 names2 = names.copy()3 print(names,names2)
当然执行结果也跟想象中是一样的:
[‘Zhangsan’,’Lisi’,’WangErgou’] [‘Zhangsan’,’Lisi’,’WangErgou’]
如果修改了其中一项元素,会不会影响复制体呢?
1 names = [‘Zhangsan’,’Lisi’,’WangErgou’]2 names2 = names.copy()3 print(names,names2)4 names[1] = “Zhaowu”5 print(names,names2)
结果显而易见,复制体和本体互不影响,结果如下:
1 [‘Zhangsan’,’Lisi’,’WangErgou’] [‘Zhangsan’,’Lisi’,’WangErgou’]2 [‘Zhangsan’,’Zhaowu’,’WangErgou’] [‘Zhangsan’,’Lisi’,’WangErgou’]
那么列表嵌套是否也适用呢,测试一下:
1 names = [‘Liuneng’,’Zhaosi’,[’SongXiaofeng’,’LiuDanaodai'],’XieGuangkun’]2 names2 = names.copy()3 print(names,names2)4 names[2][0] = ‘XieDajiao’5 print(names,names2)
额,结果好像有点不同:
1 [‘Liuneng’,’Zhaosi’,[’SongXiaofeng’,’LiuDanaodai'],'XieGuangkun'] [‘Liuneng’,’Zhaosi’,[’SongXiaofeng’,’LiuDanaodai'],’XieGuangkun’]2 [‘Liuneng’,’Zhaosi’,[’XieDajiao’,’LiuDanaodai'],’XieGuangkun’] [‘Liuneng’,’Zhaosi’,[’XieDajiao’,’LiuDanaodai'],’XieGuangkun’]
原来主列表只是存储了嵌套列表在内存中的地址,而不是所看到的数据,copy的也只是嵌套列表的地址,但两个地址指向的是内存中同一块区域,所以在对嵌套列表进行修改时,只是通过了两个复制地址而修改了真实数据,所以两个列表的元素都被改掉了。
当然,肯定会有完全独立的复制的需求,此时则需要导入一个copy模块来实现了:
copy2 names = ['zhao','qian',['sun','li'],'zhou']3 names2 = copy.copy(names)4 print(names,names2)5 names[2][0] = 'wu'6 print(names,names2)
执行之后得到结果:
1 ['zhao','qian',['sun','li'],'zhou’] ['zhao','qian',['sun','li'],'zhou’]2 ['zhao','qian',[‘wu','li'],'zhou’] ['zhao','qian',['wu','li'],'zhou']
-.-# 好吧,copy模块的copy方法和python列表的内置函数copy是一样的,想要完全复制则需要深层copy:
1 import copy2 names = ['zhao','qian',['sun','li'],'zhou']3 names2 = copy.deepcopy(names)4 print(names,names2)5 names[2][0] = 'wu'6 print(names,names2)
执行之后得到结果:
1 ['zhao','qian',['sun','li'],'zhou’] ['zhao','qian',['sun','li'],'zhou’]2 ['zhao','qian',[‘sun','li'],'zhou’] ['zhao','qian',['wu','li'],'zhou']
好了,最后终于得到的完全复制的结果。