python深拷贝和浅拷贝

import copy
from copy import deepcopy
#深拷贝和浅拷贝
lis = [1,2,3,4,[7,8,9]]
#lis2 = lis#浅拷贝
lis2=copy.deepcopy(lis)#深拷贝#结果[1, 2, 3, 4, [7, 8, 9]]
#lis2 = copy.copy(lis)#结果[1, 2, 3, 4, [7, 8, 9, 10]]
lis[-1].append(10)
print(lis2)

nums = [1,1,1,2,2,2,3,3,3,4,4,4,5,6,7,8]
for n in nums:
if n%2==0:
nums.remove(n)
#在循环列表的时候不要删元素,否则结果不对,列表根据下标取值,删除后下标变化,但是循环时候下标仍然按原来计数
print(nums)#结果[1, 1, 1, 2, 3, 3, 3, 4, 5, 7],结果里面多一个偶数2

nums = [1,1,1,2,2,2,3,3,3,4,4,4,5,6,7,8]
new_nums = copy.deepcopy(nums)#深拷贝
for n in new_nums:
if n%2==0:
nums.remove(n)
print(nums)#结果[1, 1, 1, 3, 3, 3, 5, 7]
原文地址:https://www.cnblogs.com/yuer011/p/7106336.html