假设我有一个列表字典:
d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
现在我想删除值为空列表的键值对。我尝试了这段代码:
for i in d:
if not d[i]:
d.pop(i)
但这给出了一个错误:
RuntimeError: dictionary changed size during iteration
我知道在迭代字典时不能添加或删除条目。我该如何解决这个限制以解决问题?
See Modifying a Python dict while iterating over it https://stackoverflow.com/questions/6777485/ for citations that this can cause problems, and why.
在 Python 3.x 和 2.x 中你可以使用 uselist https://docs.python.org/3/library/stdtypes.html#list强制复制密钥:
for i in list(d):
在Python 2.x中调用.keys https://docs.python.org/3/library/stdtypes.html#dict.keys制作了您可以在修改时迭代的键的副本dict
:
for i in d.keys():
但在 Python 3.x 上,.keys
返回一个查看对象 https://docs.python.org/3/library/stdtypes.html#dict-views相反,所以它不会修复你的错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)