首页 > 解决方案 > 使用“deepcopy”后的意外行为

问题描述

当我运行以下代码时,它不会修改使用'deepcopy' 生成的列表,即我得到'mt1' 不变。如果我在“mt”上应用相同的代码,我会得到想要的结果!

def subDic(f):
    w = random.randint(2, int(0.7*len(f)))
    s = random.randint(0, len(f)-w)
    idSub = {}
    for i in range(s, s+w):
        idSub[i] = f[i]
    return idSub


ft = [(2,3), (4,8), (1,0), (7,1)]
mt = copy.deepcopy(ft)
random.shuffle(mt)
mt1 = copy.deepcopy(mt)

ftDic = subDic(ft)
for e in mt1:
    if e in ftDic.values():
        mt1.remove(e)

标签: pythondeep-copy

解决方案


mt1您不应该在删除其值时进行迭代。

尝试这样的事情:

def subDic(f):
    w = random.randint(2, int(0.7*len(f)))
    s = random.randint(0, len(f)-w)
    idSub = {}
    for i in range(s, s+w):
        idSub[i] = f[i]
    return idSub


ft = [(2,3), (4,8), (1,0), (7,1)]
mt = copy.deepcopy(ft)
random.shuffle(mt)
mt1 = copy.deepcopy(mt)

ftDic = subDic(ft)
for e in ftDic.values():
    mt1.remove(e)

推荐阅读