Python enumerate reverse index only

前端 未结 10 2243
情深已故
情深已故 2021-02-05 05:43

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:



        
10条回答
  •  醉酒成梦
    2021-02-05 06:34

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

提交回复
热议问题