您的位置:首页 > 编程语言 > Python开发

python基础:映射和集合类型

2016-01-04 20:30 639 查看
python字典的迭代器遍历

字典有一个方法可以返回该字典的迭代器,这个方法就是:

dict. iteritems()


当在字典中增加或者删除字典entry的时候,迭代器会失效的,类似于C++的stl。迭代器遍历到头部就会产生错误。

>>> d = {'a': 1, 'b': 2}
>>> di = d.iteritems()
>>> di.next()
('a', 1)
>>> di.next()
('b', 2)
>>> di.next()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
StopIteration


再来看一个迭代器失效的问题:

>>> d = {'a': 1, 'b': 2}
>>> di = d.iteritems()
>>> di.next()
('a', 1)
>>> d['x'] = 'foobar'     # adding a new key:value pair during iterarion;
>>> di.next()             # that raises an error later on
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: