什么时候应该使用 iteritems() 而不是 items()?

编程入门 行业动态 更新时间:2024-10-09 13:32:32
本文介绍了什么时候应该使用 iteritems() 而不是 items()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在所有地方使用 items() 而不是 iteritems() 是否合法?为什么 iteritems() 从 Python 3 中删除?似乎是一个了不起且有用的方法.背后的原因是什么?

Is it legitimate to use items() instead of iteritems() in all places? Why was iteritems() removed from Python 3? Seems like a terrific and useful method. What's the reasoning behind it?

为了澄清,我想知道以某种方式(一次一个项目,而不是全部进入内存)以类似生成器的方式迭代字典的正确习语是什么是否与 Python 2 和 Python 3 兼容?

To clarify, I want to know what is the correct idiom for iterating over a dictionary in a generator-like way (one item at a time, not all into memory) in a way that is compatible with both Python 2 and Python 3?

推荐答案

在 Python 2.x 中 - .items() 返回(键,值)对的列表.在 Python 3.x 中,.items() 是现在是一个 itemview 对象,它的行为不同 - 所以它必须被迭代或物化......所以,list(dict.items()) 是 Python 2.x 中 dict.items() 所必需的.

In Python 2.x - .items() returned a list of (key, value) pairs. In Python 3.x, .items() is now an itemview object, which behaves different - so it has to be iterated over, or materialised... So, list(dict.items()) is required for what was dict.items() in Python 2.x.

Python 2.7 也有一些用于密钥处理的后向端口,因为您有 viewkeys、viewitems 和 viewvalues 方法,最有用的是viewkeys 的行为更像是一个 set(您期望从 dict 中获得).

Python 2.7 also has a bit of a back-port for key handling, in that you have viewkeys, viewitems and viewvalues methods, the most useful being viewkeys which behaves more like a set (which you'd expect from a dict).

简单例子:

common_keys = list(dict_a.viewkeys() & dict_b.viewkeys())

会给你一个常用键的列表,但同样,在 Python 3.x 中 - 只需使用 .keys() 代替.

Will give you a list of the common keys, but again, in Python 3.x - just use .keys() instead.

Python 3.x 通常变得更加懒惰"——即 map 现在有效地itertools.imap, zip 是 itertools.izip 等

Python 3.x has generally been made to be more "lazy" - i.e. map is now effectively itertools.imap, zip is itertools.izip, etc.

更多推荐

什么时候应该使用 iteritems() 而不是 items()?

本文发布于:2023-11-29 04:19:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645250.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:什么时候   而不是   iteritems   items

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!