Python enumerate reverse index only

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

    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)]
    
    0 讨论(0)
  • 2021-02-05 06:36

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

    [(len(range(5)) - x, x) for x in range(5)]
    
    0 讨论(0)
  • 2021-02-05 06:42

    How about using zip instead with a reversed range?

    >>> 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 izip to get a generator, also 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)
    
    0 讨论(0)
  • 2021-02-05 06:45

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

    Test:

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

    0 讨论(0)
提交回复
热议问题