对于 Python 字典,iterkeys 比 viewkeys 有什么优势吗? [英] For a Python dictionary, does iterkeys offer any advantages over viewkeys?

查看:65
本文介绍了对于 Python 字典,iterkeys 比 viewkeys 有什么优势吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Python 2.7, dictionaries have both an iterkeys method and a viewkeys method (and similar pairs for values and items), giving two different ways to lazily iterate over the keys of the dictionary. The viewkeys method provides the principal feature of iterkeys, with iter(d.viewkeys()) effectively equivalent to d.iterkeys(). Additionally, objects returned viewkeys have convenient set-like features. There thus are strong reasons to favor viewkeys over iterkeys.

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

What about the other direction? Apart from compatibility with earlier versions of Python, are there any ways in which iterkeys would be preferable to viewkeys? Would anything be lost by just always using viewkeys?

推荐答案

不,iterkeysviewkeys 没有优势,就像keys 覆盖其中任何一个.iterkeys 只是为了向后兼容.实际上,在 Python 3 中,viewkeys 是唯一仍然存在的行为,并且它已被重命名为 keys - viewkeys 方法实际上是一个向后移植 Python 3 行为.

No, there's no advantage to iterkeys over viewkeys, in the same way that there's no advantage to keys over either of them. iterkeys is only around for back compatibility. Indeed, in Python 3, viewkeys is the only behaviour that still exists, and it has been renamed to keys - the viewkeys method is actually a backport of the Python 3 behaviour.

这篇关于对于 Python 字典,iterkeys 比 viewkeys 有什么优势吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆