使用 "deepcopy" 后的意外行为

Unexpected behaviour after using "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)

您不应在删除其值时迭代 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)