Python enumerate reverse index only

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

    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)
    

提交回复
热议问题