简体   繁体   中英

How can I use enumerate to count backwards?

letters = ['a', 'b', 'c']

Assume this is my list. Where for i, letter in enumerate(letters) would be:

0, a
1, b
2, c

How can I instead make it enumerate backwards, as:

2, a
1, b
0, c

Try this:

letters = ['a', 'b', 'c']
for i, letter in reversed(list(enumerate(reversed(letters)))):
    print(i, letter)

Output:

2 a
1 b
0 c

I would try to make a reverse list first then you may use enumerate()

letters = ['a', 'b', 'c']
letters.reverse()
for i, letter in enumerate(letters)

Try this:

l = len(letters)
for i, letter in enumerate(letters):
    print(l-i, letters)

This is a great solution and works perfectly:

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
for idx, item in enumerate(items, start=-len(items)):
    print(f"reverse index for {item}: {abs(idx)}")

Here is the OUTPUT of the above snippet:

reverse index for a: 7
reverse index for b: 6
reverse index for c: 5
reverse index for d: 4
reverse index for e: 3
reverse index for f: 2
reverse index for g: 1

Here is what happening in above snippet:

  • enumerate 's start arg is given a negative value.
  • enumerate always takes a step forward.
  • Finally we use abs on idx to find absolute value, which is always positive.

tl;dr: size - index - 1

I'll assume the question you are asking is whether or not you can have the index be reversed while the item is the same, for example, the a has the ordering number of 2 when it actually has an index of 0.

To calculate this, consider that each element in your array or list wants to have the index of the item with the same "distance" (index wise) from the end of the collection. Calculating this gives you size - index.

However, many programming languages start arrays with an index of 0. Due to this, we would need to subtract 1 in order to make the indices correspond properly. Consider our last element, with an index of size - 1. In our original equation, we would get size - (size - 1), which is equal to size - size + 1, which is equal to 1. Therefore, we need to subtract 1.

Final equation (for each element): size - index - 1

zip函数为两个参数列表创建元素对的列表。

list(zip([i for i in range(len(letters))][::-1], letters))
letters = ['a', 'b', 'c']

for i, letter in zip(range(len(letters)-1, -1, -1), letters):
    print(i, letter)

prints

2 a
1 b
0 c

Taken from answer in a similar question: Traverse a list in reverse order in Python

We can define utility function (in Python3.3+ )

from itertools import count


def enumerate_ext(iterable, start=0, step=1):
    indices = count(start, step)
    yield from zip(indices, iterable)

and use it directly like

letters = ['a', 'b', 'c']
for index, letter in enumerate_ext(letters,
                                   start=len(letters) - 1,
                                   step=-1):
    print(index, letter)

or write helper

def reverse_enumerate(sequence):
    yield from enumerate_ext(sequence,
                             start=len(sequence) - 1,
                             step=-1)

and use it like

for index, letter in reverse_enumerate(letters):
    print(index, letter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM