# 在Python中以相反顺序遍历一个列表

` `>>> a = ["foo", "bar", "baz"] >>> for i in reversed(a): ... print i ... baz bar foo` `

` `>>> for i, e in reversed(list(enumerate(a))): ... print i, e ... 2 baz 1 bar 0 foo` `

` `for item in my_list[::-1]: print item` `

（或者你想在for循环中做什么。）

`[::-1]`切片反转for循环中的列表（但不会永久修改您的列表）。

` `def reverse_enum(L): for index in reversed(xrange(len(L))): yield index, L[index] L = ['foo', 'bar', 'bas'] for index, item in reverse_enum(L): print index, item` `

``` 我在范围内（len（集合）-1，-1，-1）：
打印collections[i]

```

Fyi， `help`function是非常有用的，因为它可以让你从Python控制台查看文档，例如：

`help(range)`

`reversed`内build函数很方便：

` `for item in reversed(sequence):` `

` `import itertools def reversed_enumerate(sequence): return itertools.izip( reversed(xrange(len(sequence))), reversed(sequence), )` `

` `((i, sequence[i]) for i in reversed(xrange(len(sequence))))` `
` `>>> l = ["a","b","c","d"] >>> l.reverse() >>> l ['d', 'c', 'b', 'a']` `

` `>>> print l[::-1] ['d', 'c', 'b', 'a']` `

` `>>> foo = ['1a','2b','3c','4d'] >>> for i in range(len(foo)): ... print foo[-(i+1)] ... 4d 3c 2b 1a >>>` `

` `>>> length = len(foo) >>> for i in range(length): ... print foo[length-i-1] ... 4d 3c 2b 1a >>>` `

` `collection = ['a','b','c'] [item for item in reversed( collection ) ]` `
` `def reverse(spam): k = [] for i in spam: k.insert(0,i) return "".join(k)` `

` `myArray = [1,2,3,4] myArray.reverse() for x in myArray: print x` `

` `>>> a = ["foo", "bar", "baz"] >>> for i in range(-1, -1*(len(a)+1), -1): ... print i, a[i] ... -1 baz -2 bar -3 foo` `

` `i = len(collection)-1 while i>=0: value = collection[i] index = i i-=1` `

` `for i in range(1,len(arr)+1): print(arr[-i])` `

` `a = [1, 2, 3, 4, 5, 6, 7] for x in xrange(len(a)): x += 1 print a[-x]` `