From: W. Trevor King Date: Mon, 16 Aug 2010 19:16:05 +0000 (-0400) Subject: Added hooke.util.itertools with reverse_enumerate X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=5aecd0adef8b2ec2dd78151c4ac27ee6351c4efa;p=hooke.git Added hooke.util.itertools with reverse_enumerate --- diff --git a/hooke/util/itertools.py b/hooke/util/itertools.py new file mode 100644 index 0000000..5d12aa4 --- /dev/null +++ b/hooke/util/itertools.py @@ -0,0 +1,34 @@ +# Copyright + +from __future__ import absolute_import + +from itertools import izip + + +def reverse_enumerate(x): + """Iterate through `enumerate(x)` backwards. + + This is a memory-efficient version of `reversed(list(enumerate(x)))`. + + + Examples + -------- + >>> a = ['a', 'b', 'c'] + >>> it = reverse_enumerate(a) + >>> type(it) + + >>> list(it) + [(2, 'c'), (1, 'b'), (0, 'a')] + >>> list(reversed(list(enumerate(a)))) + [(2, 'c'), (1, 'b'), (0, 'a')] + + Notes + ----- + `Original implemenation`_ by Christophe Simonis. + + .. _Original implementation: + http://christophe-simonis-at-tiny.blogspot.com/2008/08/python-reverse-enumerate.html + """ + return izip(xrange(len(x)-1, -1, -1), reversed(x)) + +# LocalWords: itertools