Python enumerate reverse index only

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

    We can use enumerate with 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
    $  
    

提交回复
热议问题