サマリー:exam = { 'math': '95', 'eng': '96', 'chn': '90', 'phy': '', 'chem': '' }使用下列遍歷的方法刪除:1. for e in exam:2. if exam[e] ==
exam = { 'math': '95', 'eng': '96', 'chn': '90', 'phy': '', 'chem': '' }
使用下列遍歷的方法刪除:
1. for e in exam:
2. if exam[e] == '':
3. del exam[e]
結(jié)果出現(xiàn)下列錯誤,怎么解決:
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循環(huán)中,相當于對鏈表的操作,它會自動調(diào)用next方法!
字典的迭代器會遍歷它的鍵,在這個過程中,不能改變這個字典!不能刪除、添加數(shù)據(jù)
要先記錄要刪除的元素的索引,遍歷完后再刪除,exam.keys()返回的是一個獨立的列表
更多關(guān)于完美解決python遍歷刪除字典里值為空的元素報錯問題請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!