I am trying to reverse the index given by enumerate
whilst retaining the original order of the list being enumerated.
Assume I have the following:
import itertools
def reversed_enumerate(seq):
return itertools.izip(reversed(range(len(seq))), reversed(seq))
Substitute zip
for itertools.izip
:)
Actually I'm using the same logic as @RemcoGerlich did, but I use list comprehension
directly, which make the code now become 1-liner:
def generatelist(x):
return [(x-1-i,n) for i,n in enumerate(range(x))]
Regarding the dilemma of choosing generator
or list comprehension
, here is the suggested way:
Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension.
We can use enumerate with len:
$ cat enumerate.py
arr = ['stone', 'cold', 'steve', 'austin']
for i, val in enumerate(arr):
print ("enu {} val {}".format(i, val))
for i, val in enumerate(arr):
print ("enu {} val {}".format(len(arr) - i - 1, val))
$ python enumerate.py
enu 0 val stone
enu 1 val cold
enu 2 val steve
enu 3 val austin
enu 3 val stone
enu 2 val cold
enu 1 val steve
enu 0 val austin
$
values = 'abcde'
for i, value in zip(reversed(range(len(values))), values):
print(i, value)
Explanation:
values = 'abcde'
values_len = len(values) # 5
indexes = range(values_len) # [0, 1, 2, 3, 4]
reversed_indexes = reversed(indexes) # [4, 3, 2, 1, 0]
# combine reversed indexes and values
reversed_enumerator = zip(reversed_indexes, values)
for i, value in reversed_enumerator:
print(i, value)
If you're going to re-use it several times, you can make your own generator:
def reverse_enum(lst):
for j, item in enumerate(lst):
yield len(lst)-1-j, item
print list(reverse_enum(range(5)))
# [(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)]
or
def reverse_enum(lst):
return ((len(lst)-1-j, item) for j, item in enumerate(lst))
Just take the length of your list and subtract the index from that...
L = range(5)
for i, n in L:
my_i = len(L) -1 - i
...
Or if you really need a generator:
def reverse_enumerate(L):
# Only works on things that have a len()
l = len(L)
for i, n in enumerate(L):
yield l-i-1, n
enumerate()
can't possibly do this, as it works with generic iterators. For instance, you can pass it infinite iterators, that don't even have a "reverse index".