Python仅枚举反向索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38738548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:22:12  来源:igfitidea点击:

Python enumerate reverse index only

pythonpython-3.xreverseenumerate

提问by rozzy

I am trying to reverse the index given by enumeratewhilst retaining the original order of the list being enumerated.

我试图enumerate在保留被枚举列表的原始顺序的同时反转给定的索引。

Assume I have the following:

假设我有以下内容:

>> range(5)
[0, 1, 2, 3, 4]

If I enumerate this I would get the following:

如果我枚举这个,我会得到以下信息:

>> list(enumerate(range(5)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

However I want to reverse the index provided by enumerate so that I get:

但是我想反转 enumerate 提供的索引,以便我得到:

[(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)]

So far I have the following code:

到目前为止,我有以下代码:

reversed(list(enumerate(reversed(range(5)))))

I was just wondering if there was a neater way to do this?

我只是想知道是否有更简洁的方法来做到这一点?

回答by Netwave

How about using zip instead with a reversed range?

如何使用 zip 而不是反向范围?

>>> zip(range(9, -1, -1), range(10))
[(9, 0), (8, 1), (7, 2), (6, 3), (5, 4), (4, 5), (3, 6), (2, 7), (1, 8), (0, 9)]


>>> def reversedEnumerate(l):
        return zip(range(len(l)-1, -1, -1), l)
>>> reversedEnumerate(range(10))
[(9, 0), (8, 1), (7, 2), (6, 3), (5, 4), (4, 5), (3, 6), (2, 7), (1, 8), (0, 9)]

As @julienSpronk suggests, use izipto get a generator, also xrange:

正如@julienSpronk 所建议的,用于izip获取生成器,还有xrange

import itertools
>>> import itertools
>>> def reversedEnumerate(l):
...     return itertools.izip(xrange(len(l)-1, -1, -1), l)
...     
>>> reversedEnumerate(range(10))
<itertools.izip object at 0x03749760>
>>> for i in reversedEnumerate(range(10)):
...     print i
...     
(9, 0)
(8, 1)
(7, 2)
(6, 3)
(5, 4)
(4, 5)
(3, 6)
(2, 7)
(1, 8)
(0, 9)

回答by mandrewcito

I don't know if this solution is better for you, but at least it's shorter:

我不知道这个解决方案是否对你更好,但至少它更短:

>>> [(4 - x, x) for x in range(5)]
[(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)]

回答by RemcoGerlich

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".

enumerate()不可能这样做,因为它适用于通用迭代器。例如,您可以将无限迭代器传递给它,甚至没有“反向索引”。

回答by Emil

Assuming your list is not long and you will not run into performance errors, you may use list(enumerate(range(5)[::-1]))[::-1].

假设您的列表不长并且您不会遇到性能错误,您可以使用list(enumerate(range(5)[::-1]))[::-1].

Test:

测试:

>>> list(enumerate(range(5)[::-1]))[::-1] [(0, 4), (1, 3), (2, 2), (3, 1), (4, 0)]

>>> list(enumerate(range(5)[::-1]))[::-1] [(0, 4), (1, 3), (2, 2), (3, 1), (4, 0)]

回答by MaThMaX

Actually I'm using the same logic as @RemcoGerlich did, but I use list comprehensiondirectly, which make the code now become 1-liner:

实际上我使用与@RemcoGerlich 相同的逻辑,但我list comprehension直接使用,这使得代码现在变成了 1-liner:

def generatelist(x):
    return [(x-1-i,n) for i,n in enumerate(range(x))]

Regarding the dilemma of choosing generatoror list comprehension, hereis the suggested way:

关于选择generatoror的困境list comprehension这里是建议的方式:

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.

基本上,如果您所做的只是迭代一次,请使用生成器表达式。如果您想存储和使用生成的结果,那么最好使用列表理解。

回答by Julien Spronck

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))

回答by John

Simply use len(lst)-ieverywhere i is used. or:

只需在使用len(lst)-ii 的地方使用即可。或者:

[(len(range(5)) - x, x) for x in range(5)]

回答by tzot

Python 2

蟒蛇 2

import itertools

def reversed_enumerate(seq):
    return itertools.izip(reversed(range(len(seq))), reversed(seq))

Python 3

蟒蛇 3

Substitute zipfor itertools.izip:)

替代zipitertools.izip:)

回答by Alexander Fedorov

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)

回答by Venfah Nazir

We can use enumerate with len:

我们可以将 enumerate 与 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
$