什么是dict_keys,dict_items和dict_values [英] what is dict_keys, dict_items and dict_values
问题描述
collections.Counter
的viewkeys(),viewitems()和viewvalues()方法时,我遇到了这三种类型。 这三个方法返回的值为 dict_keys
, dict_items
和 dict_values
。
正如我注意到的那样,它们是可迭代的。
但我的问题是:
- 为什么这三种类型存在?或者他们的用法是什么?
2.7中的新功能文档是这些引入的一个地方。引入了这些意见(提出了 here )for Python 3(和backported到2.7,正如你所看到的),作为他们提到的dict的全部世界。
在我们有键
/ 值
/ 项目
简单列出的方法。这通过复制dict的信息浪费了内存,我们有 iterkeys
/ itervalues
/ iteritems
方法没有浪费这个记忆,但不是非常有用(你唯一可以做的是迭代他们,你只能这样做一次)。这些新视图具有逻辑功能,例如设置操作,高效比较和多次迭代。
I came across these three types when I used collections.Counter
's viewkeys(),viewitems() and viewvalues() method.
The value those three methods returned are of type dict_keys
, dict_items
and dict_values
.
They are iterable, as I have noticed.
But my question is:
- why do these three types exist? Or what's their usage?
The What's new in 2.7 document is one place these are introduced. These "views" were introduced (proposed here) for Python 3 (and backported to 2.7, as you've seen) to serve as a best-of-all-worlds for the pieces of the dict they refer to.
Before we had the keys
/values
/items
methods which simply made lists. This wastes memory by copying the dict's information and we had the iterkeys
/itervalues
/iteritems
methods that didn't waste this memory but weren't very featureful (the only thing you could do is iterate over them, and you could only do so once). These new views have logical features, such as set operations, efficient comparison, and being iterable multiple times.
这篇关于什么是dict_keys,dict_items和dict_values的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!