Python 2.7 视图、for/in 和修改能很好地协同工作吗?
Do Python 2.7 views, for/in, and modification work well together?
Python 文档给出了关于在遍历字典时尝试修改字典的警告。这适用于视图吗?
我理解视图是 "live",因为如果您更改基础字典,视图会自动反映更改。我还知道如果添加或删除元素,字典的自然顺序会发生变化。这如何与 for/in 结合使用?你能安全地修改 dict 而不会弄乱循环吗?
d = dict()
# assume populated dict
for k in d.viewkeys():
# possibly add or del element of d
for/in 循环是否也遍历所有新元素?它是否缺少元素(因为顺序更改)?
是的,这适用于键或项的字典视图,因为它们提供字典内容的实时视图。在遍历字典视图时,您[=17=]不能向字典添加或删除键,因为正如您所说,这会改变字典顺序。
演示证明确实如此:
>>> d = {'foo': 'bar'}
>>> for key in d.viewkeys():
... d['spam'] = 'eggs'
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
>>> d = {'foo': 'bar', 'spam': 'eggs'}
>>> for key in d.viewkeys():
... del d['spam']
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
您可以更改值,即使在遍历值视图时也是如此,因为字典的大小不会改变,并且键保持相同的顺序。
Python 文档给出了关于在遍历字典时尝试修改字典的警告。这适用于视图吗?
我理解视图是 "live",因为如果您更改基础字典,视图会自动反映更改。我还知道如果添加或删除元素,字典的自然顺序会发生变化。这如何与 for/in 结合使用?你能安全地修改 dict 而不会弄乱循环吗?
d = dict()
# assume populated dict
for k in d.viewkeys():
# possibly add or del element of d
for/in 循环是否也遍历所有新元素?它是否缺少元素(因为顺序更改)?
是的,这适用于键或项的字典视图,因为它们提供字典内容的实时视图。在遍历字典视图时,您[=17=]不能向字典添加或删除键,因为正如您所说,这会改变字典顺序。
演示证明确实如此:
>>> d = {'foo': 'bar'}
>>> for key in d.viewkeys():
... d['spam'] = 'eggs'
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
>>> d = {'foo': 'bar', 'spam': 'eggs'}
>>> for key in d.viewkeys():
... del d['spam']
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
您可以更改值,即使在遍历值视图时也是如此,因为字典的大小不会改变,并且键保持相同的顺序。