Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用后的意外行为";“深度复制”;_Python_Deep Copy - Fatal编程技术网

Python 使用后的意外行为";“深度复制”;

Python 使用后的意外行为";“深度复制”;,python,deep-copy,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

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

在删除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)

mt1
并没有改变,它是
ft
的混合版本。为什么您认为它没有改变?我不理解“问题”,代码似乎按预期工作。@KelvinS在
ftDic
mt1
中应该没有公共值,但是当我重复运行代码时,公共值会出现在某些运行中。。。删除的值的数量应取决于
ftDic
中的值的数量,因此
len(ftDic.values())+len(mt1)=len(ft)
@E.Aly可能问题在于,在删除其值时,您正在迭代
mt1
,请尝试类似于
[mt1.remove(E)for E in ftDic.values()]
而不是最后3行代码。@KelvinS似乎是问题所在
mt1
并没有改变,它是
ft
的混合版本。为什么您认为它没有改变?我不理解“问题”,代码似乎按预期工作。@KelvinS在
ftDic
mt1
中应该没有公共值,但是当我重复运行代码时,公共值会出现在某些运行中。。。删除的值的数量应取决于
ftDic
中的值的数量,因此
len(ftDic.values())+len(mt1)=len(ft)
@E.Aly可能问题在于,在删除其值时,您正在迭代
mt1
,请尝试类似于
[mt1.remove(E)for E in ftDic.values()]
而不是最后3行代码。@KelvinS这似乎是问题所在