python - 使用“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)
推荐阅读
- apache-spark - 我可以在 PMML(从 Spark 导出)中使用没有 One-Hot-Encoding 的 StringIndexer 吗?
- javascript - 完成 Google 表单后,如何在 Google 电子表格中现有工作表的末尾创建新行?
- python - numpy genfromtxt 读取 csv 的第一个值是否丢失?
- css - 加载第二个样式表不起作用(Shopify)
- oop - 是否可以从父类调用子类中的覆盖方法?
- r - 从r中的url中提取字符串
- angular6 - Angular6 - 自定义输入字段
- function-pointers - 在 C 中打印任何数据类型的二维数组的通用函数
- javascript - 如果文本匹配字符串,如果文本不匹配字符串
- javascript - 如何在 VSCode 上的 .js 文件中获取 GraphQL 语法功能?