如何在Python中反向迭代列表?
array = [0, 10, 20, 40] for (i = array.length() - 1; i >= 0; i--)
要获取新的反向列表,请应用反向函数并将项目收集到列表中:
反向
列表中
>>> 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
>>> xs = [0, 10, 20, 40] >>> xs[::-1] [40, 20, 10, 0]
此处介绍了扩展切片语法。另请参见文档。