exam = { 'math': '95', 'eng': '96', 'chn': '90', 'phy': '', 'chem': '' }
使用下列遍历的方法删除:
for e in exam:
if exam[e] == '':
del exam[e]
结果出现下列错误,怎么解决:
Traceback (most recent call last):
File "Untitled.py", line 3, in <module>
for e in exam:
RuntimeError: dictionary changed size during iteration
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
for e in exam.keys(): if exam[e] == '': del exam[e]使用的是迭代器,它等于:
>>> exam = { 'math': '95', 'eng': '96', 'chn': '90', 'phy': '', 'chem': '' } >>> fetch = iter(exam) >>> while True: ... try: ... key = fetch.next() ... except StopIteration: ... break ... if exam[key] == '': ... del exam[key] ...只是在for循环中,它会自动调用next方法!
字典的迭代器会遍历它的键,在这个过程中,不能改变这个字典!exam.keys()返回的是一个独立的列表。
下面是来自PEP234的snapshot:
在使用迭代器遍历的过程中不能删除、添加数据
先记录要删除的元素的索引,遍历完后再删除
for k, v in exam.items(): if not v: exam.pop(k)