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


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


当前回答

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

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]))

其他回答

使用一些逻辑

用一些老派的逻辑来练习面试。

从前到后交换数字。使用两个指针索引[0]和索引[last]

def reverse(array):
    n = array
    first = 0
    last = len(array) - 1
    while first < last:
      holder = n[first]
      n[first] = n[last]
      n[last] = holder
      first += 1
      last -= 1
    return n

input -> [-1 ,1, 2, 3, 4, 5, 6]
output -> [6, 5, 4, 3, 2, 1, -1]
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 

use

print(list(reversed(list_name)))

将你的需求转换成Python的最直接的方法是这样的for语句:

for i in xrange(len(array) - 1, -1, -1):
   print i, array[i]

这是相当神秘的,但可能有用。

The cute Solution


class List_reverse():
    def reverse_list(self):
        list = [1, 2, 3, 4, 5, 6]
        list1 = []
        for i in range(1, len(list)+1):
            list1.append(list[-i])
        print(list1)


if __name__ == "__main__":
    obj = List_reverse()
    obj.reverse_list()
    enter code here