Python enumerate reverse index only

前端 未结 10 2249
情深已故
情深已故 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:32

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

提交回复
热议问题