From 5aecd0adef8b2ec2dd78151c4ac27ee6351c4efa Mon Sep 17 00:00:00 2001 From: "W. Trevor King" Date: Mon, 16 Aug 2010 15:16:05 -0400 Subject: [PATCH] Added hooke.util.itertools with reverse_enumerate --- hooke/util/itertools.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 hooke/util/itertools.py 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 -- 2.26.2