最原始的代码段:
#author:Mary names=["zhangsan", "lisi", "wangwu",[ "mary","joy"],"zhaoliu","xiaobing"] names2=names.copy() print(names) print(names2) names[2]=" 王五" names[3][0]="MARY" print(names) print(names2)
刚刚犯了错,直接把names.copy() 写成copy(names)
编译结果
D:\Python36\python.exe C:/Users/10571/PycharmProjects/untitled/day1/day2/__init__.py
['zhangsan', 'lisi', 'wangwu', ['mary', 'joy'], 'zhaoliu', 'xiaobing']
['zhangsan', 'lisi', 'wangwu', ['mary', 'joy'], 'zhaoliu', 'xiaobing']
['zhangsan', 'lisi', ' 王五', ['MARY', 'joy'], 'zhaoliu', 'xiaobing']
['zhangsan', 'lisi', 'wangwu', ['MARY', 'joy'], 'zhaoliu', 'xiaobing']
改names跟names2,结果都一样
引入copy模块,使用浅copy函数,结果跟上面一样
#author:Mary import copy names=["zhangsan", "lisi", "wangwu",[ "mary","joy"],"zhaoliu","xiaobing"] names2=copy.copy(names) print(names) print(names2) names[2]=" 王五" names[3][0]="MARY" print(names) print(names2)
D:\Python36\python.exe C:/Users/10571/PycharmProjects/untitled/day1/day2/__init__.py ['zhangsan', 'lisi', 'wangwu', ['mary', 'joy'], 'zhaoliu', 'xiaobing'] ['zhangsan', 'lisi', 'wangwu', ['mary', 'joy'], 'zhaoliu', 'xiaobing'] ['zhangsan', 'lisi', ' 王五', ['MARY', 'joy'], 'zhaoliu', 'xiaobing'] ['zhangsan', 'lisi', 'wangwu', ['MARY', 'joy'], 'zhaoliu', 'xiaobing']Process finished with exit code 0
深copy
#author:Mary import copy names=["zhangsan", "lisi", "wangwu",[ "mary","joy"],"zhaoliu","xiaobing"] names2=copy.deepcopy(names) print(names) print(names2) names[2]=" 王五" names[3][0]="MARY" print(names) print(names2)结果:D:\Python36\python.exe C:/Users/10571/PycharmProjects/untitled/day1/day2/__init__.py ['zhangsan', 'lisi', 'wangwu', ['mary', 'joy'], 'zhaoliu', 'xiaobing'] ['zhangsan', 'lisi', 'wangwu', ['mary', 'joy'], 'zhaoliu', 'xiaobing'] ['zhangsan', 'lisi', ' 王五', ['MARY', 'joy'], 'zhaoliu', 'xiaobing'] ['zhangsan', 'lisi', 'wangwu', ['mary', 'joy'], 'zhaoliu', 'xiaobing']Process finished with exit code 0