什么是dict_keys,dict_items和dict_values? [英] What are dict_keys, dict_items and dict_values?

查看:170
本文介绍了什么是dict_keys,dict_items和dict_values?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用collections.Counter的viewkeys(),viewitems()和viewvalues()方法时,遇到了这三种类型.

I came across these three types when I used collections.Counter's viewkeys(), viewitems() and viewvalues() methods.

这三个方法返回的值的类型为dict_keysdict_itemsdict_values.

The values those three methods returned are of types 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?

推荐答案

2.7文档中的新增功能是其中介绍的一个地方.针对Python 3引入了这些视图"(建议此处))(并反向移植)达到2.7(如您所见),以作为它们所引用的dict片段的最佳选择.

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.

在使用keys/values/items方法创建列表之前.这会通过复制dict的信息来浪费内存,而我们使用的iterkeys/itervalues/iteritems方法不会浪费内存,但是功能却不那么丰富(唯一可以做的就是遍历它们,并且您只能这样做一次).这些新视图具有逻辑特征,例如设置操作,有效的比较以及可多次迭代.

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屋!

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