如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
当前回答
我很困惑为什么显而易见的选择到目前为止还没有出现:
如果reversed()不能工作,因为你有一个生成器(如enumerate()的情况),只需使用sorted():
>>> l = list( 'abcdef' )
>>> sorted( enumerate(l), reverse=True )
[(5, 'f'), (4, 'e'), (3, 'd'), (2, 'c'), (1, 'b'), (0, 'a')]
其他回答
作为python的初学者,我发现这种方法更容易理解,并且可以反转列表。
= = 1, 2, 3, 4
对于I在range(len(numlst)-1,-1,-1):
ie., for i in range(3,-1,-1), where 3 is length of list minus 1,
second -1 means list starts from last element and
third -1 signifies it will traverse in reverse order.
打印(numlst[I])
O /p = 4,3,2,1
反向函数在这里很方便:
myArray = [1,2,3,4]
myArray.reverse()
for x in myArray:
print x
你可以:
for item in my_list[::-1]:
print item
(或者你想在for循环中做的任何事情。)
[::-1]片在for循环中反转列表(但实际上不会“永久”修改列表)。
使用list.reverse(),然后像往常一样迭代。
http://docs.python.org/tutorial/datastructures.html
我很困惑为什么显而易见的选择到目前为止还没有出现:
如果reversed()不能工作,因为你有一个生成器(如enumerate()的情况),只需使用sorted():
>>> l = list( 'abcdef' )
>>> sorted( enumerate(l), reverse=True )
[(5, 'f'), (4, 'e'), (3, 'd'), (2, 'c'), (1, 'b'), (0, 'a')]