dict - python遍历删除字典里值为空的元素报错
PHPz
PHPz 2017-04-17 11:08:39
[Python讨论组]
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
PHPz
PHPz

学习是最好的投资!

全部回复(5)
阿神
for e in exam.keys():
    if exam[e] == '':
        del exam[e]
for e in exam:

使用的是迭代器,它等于:

>>> 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:

Dictionaries implement a tp_iter slot that returns an efficient
iterator that iterates over the keys of the dictionary. During
such an iteration, the dictionary should not be modified, except
that setting the value for an existing key is allowed (deletions or additions are not, nor is the update() method).
伊谢尔伦
dict(filter(lambda x: x[1] != '', exam.items()))
PHP中文网

在使用迭代器遍历的过程中不能删除、添加数据

天蓬老师

先记录要删除的元素的索引,遍历完后再删除

高洛峰
for k, v in exam.items():
    if not v: exam.pop(k)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号