python-浅拷贝&深拷贝

1、循环删除列表,为啥结果不正确?

a = [1,1,2,3,4,5]#原始下标为0,1,2,3,4,5

# 第一次循环,处理下标0,即1,满足条件,删除,结果[1,2,3,4,5],此时下标为0,1,2,3,4
# 第二次循环,处理下标1,即2,不满足
# 第三次循环,处理下标2,即3,满足条件,删除,结果[1,2,4,5],此时下标为 0,1,2,3
# 第四次循环,处理下标3,即5,满足条件,删除,结果[1,2,4]

# 结果:[1,2,4],不符合预期,为啥还有一个1??见执行过程
for i in a:
    if i % 2 != 0:
        a.remove(i)
        #print(a)

print(a) # 循环删list会导致下标错乱

解决方案:

a = [1,1,2,3,4,5]

# 解决方法
a2 = [1,1,2,3,4,5]

for i in a2:
    if i % 2 != 0:
        a.remove(i)
        #print(a)

print(a)  # 结果[[2, 4]]

2、浅拷贝&深拷贝

  • 浅拷贝:dict.copy()也是浅拷贝
a = [1,1,2,3,4,5]
a2 = a # 内存地址一样,肯定是浅拷贝
print(‘a‘,id(a))
print(‘a2‘,id(a2))

a3 = a.copy() # 浅拷贝:list自带的copy方法,内部地址不一样,不一定是深拷贝
print(‘a‘,id(a))
print(‘a3‘,id(a3))

a5 = copy.copy(a) # 浅拷贝
print(‘a‘,id(a))
print(‘a5‘,id(a5))

a4 = copy.deepcopy(a) # 深拷贝,只有这一种拷贝方式是深拷贝
print(‘a‘,id(a))
print(‘a4‘,id(a4))

3、实例??

class User:
    def __init__(self,id,status):
        self.id = id
        self.status = status

users = []
u_fail_count = 0
for i in range(20):
    u = User(i,random.choice([‘fail‘,‘success‘]))
    if u.status == ‘fail‘:
        u_fail_count += 1
    users.append(u)
print(‘失败的个数‘,u_fail_count)
print(‘成功的个数‘,20 - u_fail_count)


def delete_item(items):
    # items2 = items # 浅拷贝
    items2 = copy.deepcopy(items) # 深拷贝
    for item in items2:
        if item.status == ‘fail‘:
            items.remove(item) # ???ValueError: list.remove(x): x not in list
    return  items

result = delete_item(users)
print(len(result))

相关推荐