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


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


当前回答

>>> xs = [0, 10, 20, 40]
>>> xs[::-1]
[40, 20, 10, 0]

这里将解释扩展片语法。请参见文档。

其他回答

要获得一个新的反向列表,应用reversed函数并将项目收集到一个列表中:

>>> xs = [0, 10, 20, 40]
>>> list(reversed(xs))
[40, 20, 10, 0]

在列表中向后迭代:

>>> xs = [0, 10, 20, 40]
>>> for x in reversed(xs):
...     print(x)
40
20
10
0

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

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

可以使用__reverse__来完成,它会返回一个生成器。

>>> l = [1,2,3,4,5]
>>> for i in l.__reversed__():
...   print i
... 
5
4
3
2
1
>>>
array=[0,10,20,40]
for e in reversed(array):
  print e

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

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