简体   繁体   中英

Translate Python for loop into a while loop

How could the function that takes a list of numbers, [1,2,3 ], return the list [3,2,1] by using a while loop instead of the provided for loop. Also, what do the excessive -1's mean in the for loop.

def for_version(items):
   result = []
   for i in range(len(items) - 1, -1, -1):
      result.append(items[i])
   return result

The excessive -1 in the range(len(items) - 1, -1, -1) are, in order, the lower bound of the sequence (in case of negative step) returned and the step ( docs ).

For example, range(5, -1, -1) means list of numbers from 5 down to 0 (-1 is the exclusive boundary), step down by 1 .

As to the while loop:

def while_version(items):
    i = len(items) - 1
    result = []
    while i >= 0:
        result.append(items[i])
        i -= 1
    return result

The i variable simulates the results of range(len(items) - 1, -1, -1) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM