假设我们有一个 Python 字典d
,我们像这样迭代它:
for k, v in d.iteritems():
del d[f(k)] # remove some item
d[g(k)] = v # add a new item
(f
and g
只是一些黑盒转换。)
换句话说,我们尝试添加/删除项目d
当使用迭代它时iteritems
.
这是明确定义的吗?您能提供一些参考资料来支持您的答案吗?
See also How to avoid "RuntimeError: dictionary changed size during iteration" error? https://stackoverflow.com/questions/11941817 for the separate question of how to avoid the problem.
亚历克斯·马泰利 (Alex Martelli) 对此发表了自己的看法here https://stackoverflow.com/questions/2315520/in-python-how-do-i-loop-through-the-dictionary-and-change-the-value-if-it-equals/2315529#2315529.
在循环容器时更改容器(例如 dict)可能不安全。
所以del d[f(k)]
可能不安全。如您所知,解决方法是使用d.copy().items()
(循环遍历容器的独立副本)而不是d.iteritems()
or d.items()
(使用相同的底层容器)。
修改该值是可以的existing字典的索引,但在新索引处插入值(例如d[g(k)] = v
)可能不起作用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)