Python 3.0 - dict方法返回视图 - 为什么? [英] Python 3.0 - dict methods return views - why?

查看:131
本文介绍了Python 3.0 - dict方法返回视图 - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


dict方法dict.keys(),dict.items()
和dict.values()返回views
而不是列表。
http://docs.python.org/dev/3.0/ whatsnew // 3.0.html

首先,一个视图与迭代器不同?其次,这个变化有什么好处?这只是出于性能原因吗?

First of all how is a view different from an iterator? Secondly, what is the benefit of this change? Is it just for performance reasons?

对我来说似乎没有直觉,即我要求一个事情列表(给我所有的钥匙),而我还要再回来。这会混淆人吗?

It doesn't seem intuitive to me, i.e., I'm asking for a list of thing (give me all your keys) and I'm getting something else back. Will this confuse people?

推荐答案

你正在有一个列表。它只是不是内部列表的副本,而是表现为列表但仅表示内部状态的东西。

You are effectively getting a list. It's just not a copy of the internal list, but something that acts as if it where a list but only represents the internal state.

这与Java中的实现方式相同(以及许多其他语言/环境)。

That's the same way it's implemented in Java (and probably many other languages/environments as well).

主要原因是对于许多使用情况,返回完全分离的列表是不必要的和浪费的。这将需要复制整个内容(可能或许不是很多)。

The main reason is that for many use cases returning a completely detached list is unnecessary and wasteful. It would require copying the entire content (which may or many not be a lot).

如果您只想迭代键,则不需要创建新列表。如果您确实需要它作为单独的列表(作为副本),那么您可以从视图轻松创建该列表。

If you simply want to iterate over the keys then creating a new list is not necessary. And if you indeed need it as a separate list (as a copy) then you can easily create that list from the view.

这篇关于Python 3.0 - dict方法返回视图 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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