如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
当前回答
你也可以使用while循环:
i = len(collection)-1
while i>=0:
value = collection[i]
index = i
i-=1
其他回答
要使用负标:从-1开始,在每次迭代中后退-1。
>>> a = ["foo", "bar", "baz"]
>>> for i in range(-1, -1*(len(a)+1), -1):
... print i, a[i]
...
-1 baz
-2 bar
-3 foo
你可以:
for item in my_list[::-1]:
print item
(或者你想在for循环中做的任何事情。)
[::-1]片在for循环中反转列表(但实际上不会“永久”修改列表)。
如果你不介意指数为负,你可以这样做:
>>> a = ["foo", "bar", "baz"]
>>> for i in range(len(a)):
... print(~i, a[~i]))
-1 baz
-2 bar
-3 foo
使用list.reverse(),然后像往常一样迭代。
http://docs.python.org/tutorial/datastructures.html
无论如何,你也可以这样做。非常简单。
a = [1, 2, 3, 4, 5, 6, 7]
for x in xrange(len(a)):
x += 1
print a[-x]