如何在Python中反向迭代列表?


请参见:如何获得列表的反向副本(避免在.reverse后链接方法时使用单独的语句)?


当前回答

list_data = [1,2,3,4,5]
l = len(list_data)
i=l+1
rev_data = []
while l>0:
  j=i-l
  l-=1
  rev_data.append(list_data[-j])
print "After Rev:- %s" %rev_data 

其他回答

>>> l = [1, 2, 3, 4, 5]
>>> print(reduce(lambda acc, x: [x] + acc, l, []))
[5, 4, 3, 2, 1]

使用列表推导式:

[array[n] for n in range(len(array)-1, -1, -1)]

使用切片,例如array = array[::-1],是一个简洁的技巧,非常python化,但对于新手来说可能有点晦涩。使用reverse()方法是进行日常编码的好方法,因为它易于阅读。

然而,如果你需要在面试问题中反转列表,你可能无法使用这些内置的方法。面试官会看你如何解决问题,而不是Python知识的深度,需要一个算法的方法。下面的例子,使用一个经典的交换,可能是一种方法:-

def reverse_in_place(lst):      # Declare a function
    size = len(lst)             # Get the length of the sequence
    hiindex = size - 1
    its = size/2                # Number of iterations required
    for i in xrange(0, its):    # i is the low index pointer
        temp = lst[hiindex]     # Perform a classic swap
        lst[hiindex] = lst[i]
        lst[i] = temp
        hiindex -= 1            # Decrement the high index pointer
    print "Done!"

# Now test it!!
array = [2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654]

print array                    # Print the original sequence
reverse_in_place(array)        # Call the function passing the list
print array                    # Print reversed list


**The result:**
[2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654]
Done!
[654, 124, 24, 7, 1, 65, 60, 32, 27, 25, 19, 12, 9, 8, 5, 2]

注意,这将不适用于元组或字符串序列,因为字符串和元组是不可变的,也就是说,您不能写入它们来更改元素。

通过切换相反索引的引用来就地反转:

>>> l = [1,2,3,4,5,6,7]    
>>> for i in range(len(l)//2):
...     l[i], l[-1-i] = l[-1-i], l[i]
...
>>> l
[7, 6, 5, 4, 3, 2, 1]

下面是一种使用生成器对反向进行惰性计算的方法:

def reverse(seq):
    for x in range(len(seq), -1, -1): #Iterate through a sequence starting from -1 and increasing by -1.
        yield seq[x] #Yield a value to the generator

现在像这样迭代:

for x in reverse([1, 2, 3]):
    print(x)

如果你需要一个列表:

l = list(reverse([1, 2, 3]))