gpt4 book ai didi

python - 对于 Python 字典,iterkeys 是否比 viewkeys 提供任何优势?

转载 作者:IT老高 更新时间:2023-10-28 22:20:44 27 4
gpt4 key购买 nike

在 Python 2.7 中,字典有一个 iterkeys 方法和一个 viewkeys 方法(以及类似的值和项对),提供了两种不同的方法来懒惰地迭代字典的键。 viewkeys 方法提供了 iterkeys 的主要功能,其中 iter(d.viewkeys()) 等效于 d.iterkeys( )。此外,返回的对象 viewkeys 具有方便的类似集合的功能。因此,有充分的理由支持 viewkeys 而不是 iterkeys

另一个方向呢?除了与早期版本的 Python 兼容之外,还有什么方法可以使 iterkeys 优于 viewkeys?总是使用 viewkeys 会丢失任何东西吗?

最佳答案

字典 View 会像字典一样更新,而迭代器不一定会这样做。

这意味着如果您使用 View ,更改字典,然后再次使用 View , View 将发生更改以反射(reflect)字典的新状态。

They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes. Source

例子:

>>> test = {1: 2, 3: 4}
>>> a = test.iterkeys()
>>> b = test.viewkeys()
>>> del test[1]
>>> test[5] = 6
>>> list(a)
[3, 5]
>>> b
dict_keys([3, 5])

当改变大小时,会抛出异常:

>>> test = {1: 2, 3: 4}
>>> a = test.iterkeys()
>>> b = test.viewkeys()
>>> test[5] = 6
>>> list(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
>>> b
dict_keys([1, 3, 5])

还值得注意的是,您只能对 keyiterator 进行一次迭代:

>>> test = {1: 2, 3: 4}
>>> a = test.iterkeys()
>>> list(a)
[1, 3]
>>> list(a)
[]
>>> b = test.viewkeys()
>>> b
dict_keys([1, 3])
>>> b
dict_keys([1, 3])

关于python - 对于 Python 字典,iterkeys 是否比 viewkeys 提供任何优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10189273/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com