完美解决python遍历删除字典里值为空的元素报错问题
exam = { 'math': '95', 'eng': '96', 'chn': '90', 'phy': '', 'chem': '' }
使用下列遍历的方法删除:
1. for e in exam:
2. if exam[e] == '':
3. 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
正确做法:
1. s = {"1":a,"2":b,"3":c,"4":d,"5":e}
2. s_key = list(s.keys())
3. for k_s in s_key:
4.#比如我要删除第四个元素
5.del s["4"]
只是在for循环中,相当于对链表的操作,它会自动调用next方法!
字典的迭代器会遍历它的键,在这个过程中,不能改变这个字典!不能删除、添加数据
要先记录要删除的元素的索引,遍历完后再删除,exam.keys()返回的是一个独立的列表
相关推荐
JamesRayMurphy 2020-05-31
elizabethxxy 2020-11-06
pythonxuexi 2020-10-30
retacnyue 2020-09-28
pythonxuexi 2020-09-06
Morelia 2020-09-04
zhaobig 2020-08-17
linkequa 2020-08-16
CloudXli 2020-08-14
kikaylee 2020-08-12
LowisLucifer 2020-08-09
xiesheng 2020-08-06
Tristahong 2020-08-05
CatherineC00 2020-08-01
Andrewjdw 2020-07-26
reallyr 2020-07-18
wordmhg 2020-07-16