2024-04-27 00:46:01 发布
网友
在迭代字典时向字典添加项有多安全?乍一看是挺管用的,但我想知道是否有不安全的情况。 键是字符串0,1…等等
0
1
使用items()或keys()方法可以安全地修改dict。items()返回dict键的副本,value pairs和keys()返回dict键的副本。你知道吗
>>> foo = {'spam': 'egg'} >>> for k, v in foo.items(): ... foo['egg'] = 'spam'
迭代时不能更改词典的大小:
>>> foo = {'spam': 'egg'} >>> for i in foo: ... foo['egg'] = 'spam' ... Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: dictionary changed size during iteration
你必须先复印一份:
>>> foo = {'spam': 'egg'} >>> for i in dict(foo): ... foo['egg'] = 'spam' ... >>> foo {'spam': 'egg', 'egg': 'spam'}
使用items()或keys()方法可以安全地修改dict。items()返回dict键的副本,value pairs和keys()返回dict键的副本。你知道吗
迭代时不能更改词典的大小:
你必须先复印一份:
相关问题 更多 >
编程相关推荐