繁体   English   中英

使用“ 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM