Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get reversed enumerate in python2?

I have a list with such structure:

[(key1, val1), (key2, val2), ...]

And I want to iterate over it getting key and the index of item on each step. In reverse order.

Right now I'm doing it like this:

for index, key in reversed(list(enumerate(map(lambda x: x[0], data)))):
    print index, key

It works perfectly, but I'm just worrying if it's a properly way to do. Can there is be a better solution?

like image 296
asnelzin Avatar asked Jul 17 '14 12:07

asnelzin


People also ask

Can you enumerate backwards?

Since enumerate() returns a generator and generators can't be reversed, you need to convert it to a list first.

How do you iterate a list backwards?

We can iterate the list in reverse order in two ways: Using List. listIterator() and Using for loop method.

How do you reverse a list in Python for loops?

3) Using for loop Another way to reverse the python list without the use of any built-in methods is using loops. Create an empty list to copy the reversed elements. In the for loop, add the iterator as a list element at the beginning with the new list elements. So in that way, the list elements will be reversed.

How do I print a list of numbers backwards in Python?

But Python does have a built-in reversed function. If you wrap range() inside reversed() , then you can print the integers in reverse order. range() makes it possible to iterate over a decrementing sequence of numbers, whereas reversed() is generally used to loop over a sequence in reverse order.


1 Answers

enumerate() cannot count down, only up. Use a itertools.count() object instead:

from itertools import izip, count

for index, item in izip(count(len(data) - 1, -1), reversed(data)):

This produces a count starting at the length (minus 1), then counting down as you go along the reversed sequence.

Demo:

>>> from itertools import izip, count
>>> data = ('spam', 'ham', 'eggs', 'monty')
>>> for index, item in izip(count(len(data) - 1, -1), reversed(data)):
...     print index, item
... 
3 monty
2 eggs
1 ham
0 spam
like image 105
Martijn Pieters Avatar answered Sep 19 '22 02:09

Martijn Pieters