简体   繁体   English

如何使用枚举向后计数?

[英]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: for i, letter in enumerate(letters)将是:

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() 我会首先尝试制作一个反向列表,然后你可以使用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. enumeratestart arg给出负值。
  • enumerate always takes a step forward. enumerate总是向前迈出一步。
  • Finally we use abs on idx to find absolute value, which is always positive. 最后我们在idx上使用abs来找到绝对值,这总是正的。

tl;dr: size - index - 1 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. 我假设您要问的问题是,当项目相同时,您是否可以反转索引,例如,当实际索引为0时,a的排序编号为2。

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. 但是,许多编程语言启动索引为0的数组。因此,我们需要减去1才能使索引正确对应。 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. 考虑我们的最后一个元素,索引大小为1.在我们原始的等式中,我们得到size - (size - 1),它等于size - size + 1,等于1.因此,我们需要减去1。

Final equation (for each element): size - index - 1 最终方程(对于每个元素):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 取自类似问题的答案: 在Python中以相反的顺序遍历列表

We can define utility function (in Python3.3+ ) 我们可以定义效用函数(在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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