迭代Python 3中的字典项(),values(),keys() [英] Iterating over dictionary items(), values(), keys() in Python 3

查看:182
本文介绍了迭代Python 3中的字典项(),values(),keys()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我理解正确,在Python 2中, iter(d.keys()) d.iterkeys()。但现在, d.keys()是一个视图,它位于列表和迭代器之间。视图和迭代器有什么区别?

If I understand correctly, in Python 2, iter(d.keys()) was the same as d.iterkeys(). But now, d.keys() is a view, which is in between the list and the iterator. What's the difference between a view and an iterator?

换句话说,在Python 3中,

In other words, in Python 3, what's the difference between

for k in d.keys()
    f(k)

for k in iter(d.keys())
    f(k)

此外,这些差异如何显示在一个简单的循环(如果有的话)?

Also, how do these differences show up in a simple for loop (if at all)?

推荐答案

我不知道这是否是你的问题,但希望在这方面解释一下Python 2和3之间的区别。

在Python 2中, iter d.keys()) d.iterkeys()并不完全相同,尽管它们的行为相同。首先, keys()将返回字典的密钥列表副本,然后 iter 将返回一个迭代器对象在这个列表中,第二个是完整的密钥列表的副本永远不会被构建。

In Python 2, iter(d.keys()) and d.iterkeys() are not quite equivalent, although they will behave the same. In the first, keys() will return a copy of the dictionary's list of keys and iter will then return an iterator object over this list, with the second a copy of the full list of keys is never built.

d.keys返回的视图对象)Python 3中的可迭代(即可以从中创建一个迭代器),所以当你在d.keys()中为k表示 code> Python将为您创建迭代器。因此,您的两个示例将表现相同。

The view objects returned by d.keys() in Python 3 are iterable (i.e. an iterator can be made from them) so when you say for k in d.keys() Python will create the iterator for you. Therefore your two examples will behave the same.

更改 keys()的返回类型的意义是Python 3视图对象是动态的。即如果我们说 ks = d.keys(),然后添加到 d 然后 ks 将反映这一点。在Python 2中, keys()返回dict中当前所有键的列表。比较:

The significance in the change of the return type for keys() is that the Python 3 view object is dynamic. i.e. if we say ks = d.keys() and later add to d then ks will reflect this. In Python 2, keys() returns a list of all the keys currently in the dict. Compare:

Python 3

>>> d = { "first" : 1, "second" : 2 }
>>> ks = d.keys()
>>> ks
dict_keys(['second', 'first'])
>>> d["third"] = 3
>>> ks
dict_keys(['second', 'third', 'first'])

Python 2.x

>>> d = { "first" : 1, "second" : 2 }
>>> ks = d.keys()
>>> ks
['second', 'first']
>>> d["third"] = 3
>>> ks
['second', 'first']

作为Python 3的 keys()返回Python 3没有(并且不需要)单独的 iterkeys 方法的动态对象。

As Python 3's keys() returns the dynamic object Python 3 doesn't have (and has no need for) a separate iterkeys method.

进一步的澄清

在Python 3中, keys() / code>返回一个 dict_keys 对象,但如果我们在中使用它循环上下文在d.keys()中的k中,则隐式创建迭代器。因此,在d()()中的k的d.keys()中的k的区别在于(d.keys())是迭代器的隐式和显式创建之一。

In Python 3, keys() returns a dict_keys object but if we use it in a for loop context for k in d.keys() then an iterator is implicitly created. So the difference between for k in d.keys() and for k in iter(d.keys()) is one of implicit vs. explicit creation of the iterator.

在另一个区别方面,虽然它们都是动态的,但请记住,如果我们创建一个显式迭代器,那么它只能使用一次,而视图可以根据需要重复使用。例如

In terms of another difference, whilst they are both dynamic, remember if we create an explicit iterator then it can only be used once whereas the view can be reused as required. e.g.

>>> ks = d.keys()
>>> 'first' in ks
True
>>> 'second' in ks
True
>>> i = iter(d.keys())
>>> 'first' in i
True
>>> 'second' in i
False             # because we've already reached the end of the iterator

另外,请注意,如果我们创建一个显式迭代器,然后修改dict,则迭代器无效:

Also, notice that if we create an explicit iterator and then modify the dict then the iterator is invalidated:

>>> i2 = iter(d.keys())
>>> d['fourth'] = 4
>>> for k in i2: print(k)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

在Python 2中,给定 keys 需要一种单独的方法来提供一种迭代方式,而不复制密钥列表,同时仍保持向后兼容性。因此 iterkeys()

In Python 2, given the existing behaviour of keys a separate method was needed to provide a way to iterate without copying the list of keys whilst still maintaining backwards compatibility. Hence iterkeys()

这篇关于迭代Python 3中的字典项(),values(),keys()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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