描述
copy() 方法用于在复制列表。
语法
list.copy()
参数
- obj -- 复制对象,浅copy。
返回值
该方法无返回值,但是会复制一份原来的列表。
实例
append()函数的使用方法:
浅 copy
1 #Author:Junce Liu 2 City = ["杭州","苏州","广州",[1,4,‘liu‘],"苏州","通州","扬州","苏州"] 3 City2 = City.copy() 4 print(City) 5 print("一次copy:",City2) 6 City[1] = "香港" # 将City索引1为“广州”,更改为‘香港’。 7 City[3][1] = "柳峻熙" # 将嵌套的列表索引1为4更改为“亚洲” 8 print(City) 9 print("二次copy:",City2) 10 11 输出显示如下: 12 [‘杭州‘, ‘苏州‘, ‘广州‘, [1, 4, ‘liu‘], ‘苏州‘, ‘通州‘, ‘扬州‘, ‘苏州‘] 13 一次copy: [‘杭州‘, ‘苏州‘, ‘广州‘, [1, 4, ‘liu‘], ‘苏州‘, ‘通州‘, ‘扬州‘, ‘苏州‘] 14 [‘杭州‘, ‘香港‘, ‘广州‘, [1, ‘亚洲‘, ‘liu‘], ‘苏州‘, ‘通州‘, ‘扬州‘, ‘苏州‘] 15 二次copy: [‘杭州‘, ‘苏州‘, ‘广州‘, [1, ‘亚洲‘, ‘liu‘], ‘苏州‘, ‘通州‘, ‘扬州‘, ‘苏州‘]
看到最后一步的打印可能会感觉奇怪,为什么两次打印结果不一样啊?
实例 02
深copy,这个不建议用
1 #Author:Junce Liu 2 import copy 3 City = ["杭州","苏州","广州",[1,4,‘liu‘],"苏州","通州","扬州","苏州"] 4 City2 = City.deepcopy() 5 print(City) 6 print("一次copy:",City2) 7 City[1] = "香港" 8 City[3][1] = "柳峻熙" 9 print(City) 10 print("二次copy:",City2) 11 print(City2) 12 13 输出结果如下: 14 [‘杭州‘, ‘苏州‘, ‘广州‘, [1, 4, ‘liu‘], ‘苏州‘, ‘通州‘, ‘扬州‘, ‘苏州‘] 15 一次copy: [‘杭州‘, ‘苏州‘, ‘广州‘, [1, 4, ‘liu‘], ‘苏州‘, ‘通州‘, ‘扬州‘, ‘苏州‘] 16 [‘杭州‘, ‘香港‘, ‘广州‘, [1, ‘柳峻熙‘, ‘liu‘], ‘苏州‘, ‘通州‘, ‘扬州‘, ‘苏州‘] 17 二次copy: [‘杭州‘, ‘苏州‘, ‘广州‘, [1, ‘柳峻熙‘, ‘liu‘], ‘苏州‘, ‘通州‘, ‘扬州‘, ‘苏州‘] 18 [‘杭州‘, ‘苏州‘, ‘广州‘, [1, 4, ‘liu‘], ‘苏州‘, ‘通州‘, ‘扬州‘, ‘苏州‘]
时间: 2024-12-23 17:48:55