Python 使用后的意外行为";“深度复制”;
当我运行以下代码时,它不会修改使用“deepcopy”生成的列表,也就是说,我得到的“mt1”没有改变。如果我在“mt”上应用相同的代码,我会得到期望的结果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
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这似乎是问题所在