问题描述
显然,在 Python 2.X 中几乎在每个实例中使用 values
、items
和 keys
都是不好的做法,因为您将分配一个您实际上不需要的额外列表.因此,有一段时间,推荐的最佳实践是使用 iteritems
/itervalues
,如果你想使用内置的 __iter__
枚举 dict
的键.
Obviously, using values
, items
, and keys
is bad practice in Python 2.X in virtually every instance, because you'll allocate an extra list you don't actually need. Thus, for some time, the recommended best practice was to use iteritems
/itervalues
, and to use the built-in __iter__
if you wanted to enumerate the dict
's keys.
将 Python 3 的 keys
、values
和 items
作为 viewkeys
向后移植到 Python 2.7,viewvalues
和 viewitems
,我想知道 view*
函数系列与它们的 iter 的实际性能权衡是什么*
对应.是继续使用面向 Python 2.6 及更早版本的 iter*
函数的唯一原因,还是旧的 iter*
方法比新的 视图更快*
特定上下文中的方法?
With the backport of Python 3's keys
, values
, and items
to Python 2.7 as viewkeys
, viewvalues
, and viewitems
, I'm wondering what the actual performance tradeoffs are of the view*
family of functions, vs. their iter*
counterparts. Is the only reason to continue using the iter*
functions that you are targeting Python 2.6 and earlier, or can the older iter*
methods be faster than the newer view*
methods in certain contexts?
推荐答案
这里有一个解决 iterkeys
与 viewkeys
的答案:https://stackoverflow.com/a/10190228/344143
Here's an answer addressing iterkeys
vs. viewkeys
here: https://stackoverflow.com/a/10190228/344143
总结(有一点背景故事):view*
方法是数据的实时视图(会随着数据的更新而更新),而 iter*
和只是-普通的 *
更像是快照.
Summary (with a little backstory): view*
methods are a live view into the data (that will update as it updates), whereas iter*
and just-plain *
are more like snapshots.
链接的回答者表明,虽然 view*
风格的方法也可能具有较小的性能优势,但向后移植可能存在兼容性问题,并建议继续使用 iter*
/*
在 Python 2 下.
The linked answerer suggests that while the view*
-flavored methods may have a minor performance edge as well, there may be compatibility issues with the backport, and recommends continuing to use iter*
/*
under Python 2.
我的看法:如果您想要实时视图并且您使用的是 Python 2,请使用 view*
;如果您只想快速浏览一组键/值/项目,请使用 iter*
;如果您想继续使用 k/v/i 的快照(或以某种非线性方式进行迭代),请使用 *
.让性能下滑,直到你在内循环中找到它.
My take: if you want a live view and you're under Python 2, use view*
; if you just want to whip through the set of keys/values/items once, use iter*
; if you want to hang on to a snapshot of k/v/i for a bit (or iterate in some non-linear fashion), use *
. Let the performance slide until you pick it up in an inner loop.
这篇关于在 Python 2 中,viewvalues()/viewitems() 与 itervalues()/iteritems() 的性能权衡是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!