使用“ deepcopy”后出现意外行为

时间:2018-10-13 01:54:38

标签: python deep-copy

当我运行以下代码时,它不会修改使用'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)

1 个答案:

答案 0 :(得分:2)

在删除其值时,请勿迭代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)