Python Traverse list reverse order
来源:互联网 发布:python find函数实现 编辑:程序博客网 时间:2024/06/05 22:37
Traverse a list in reverse order in Python
So I can start from len(collection)
and end in collection[0]
.
EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.
13 Answers
Use the reversed()
built-in function:
>>> a = ["foo", "bar", "baz"]>>> for i in reversed(a):... print i... bazbarfoo
To also access the original index:
>>> for i, e in reversed(list(enumerate(a))):... print i, e... 2 baz1 bar0 foo
You can do:
for item in my_list[::-1]: print item
(Or whatever you want to do in the for loop.)
The [::-1]
slice reverses the list in the for loop (but won't actually modify your list "permanently").
[::-1]
creates a shallow copy, therefore it doesn't change the array neither "permanently" nor "temporary".– J.F. Sebastian Feb 9 '09 at 19:15len(my_list)
), end point: unspecified (defaults to start of list - 0
) and step: -1
(iterate backwards through the list, 1 item at a time) – Edward Nov 29 '15 at 16:48 If you need the loop index, and don't want to traverse the entire list twice, or use extra memory, I'd write a generator.
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
reversed(xrange(len(L)))
produces the same indices as xrange(len(L)-1, -1, -1)
. – J.F. Sebastian Feb 10 '09 at 16:52for index, item in enumerate(reversed(L)): print len(L)-1-index, item
– Don Kirkby Nov 5 '14 at 21:56It can be done like this:
for i in range(len(collection)-1, -1, -1): print collection[i]
So your guess was pretty close :) A little awkward but it's basically saying: start with 1 less than len(collection)
, keep going until you get to just before -1, by steps of -1.
Fyi, the help
function is very useful as it lets you view the docs for something from the Python console, eg:
help(range)
-1
's. I would just say reversed(xrange(len(collection)))
– musiphil Sep 7 '13 at 1:18The reversed
builtin function is handy:
for item in reversed(sequence):
The documentation for reversed explains its limitations.
For the cases where I have to walk a sequence in reverse along with the index (e.g. for in-place modifications changing the sequence length), I have this function defined an my codeutil module:
import itertoolsdef reversed_enumerate(sequence): return itertools.izip( reversed(xrange(len(sequence))), reversed(sequence), )
This one avoids creating a copy of the sequence. Obviously, the reversed
limitations still apply.
How about without recreating a new list, you can do by indexing:
>>> foo = ['1a','2b','3c','4d']>>> for i in range(len(foo)):... print foo[-(i+1)]...4d3c2b1a>>>
OR
>>> length = len(foo)>>> for i in range(length):... print foo[length-i-1]...4d3c2b1a>>>
Use list.reverse()
and then iterate as you normally would.
http://docs.python.org/tutorial/datastructures.html
The other answers are good, but if you want to do as List comprehension style
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)
>>> l = ["a","b","c","d"]>>> l.reverse()>>> l['d', 'c', 'b', 'a']
OR
>>> print l[::-1]['d', 'c', 'b', 'a']
- Python Traverse list reverse order
- Reverse traverse
- Python reverse order
- Python list reverse
- Python List reverse()方法
- List::traverse遍历
- Leetcode-Reverse Linked List-Python
- 【Python】Python3 List reverse()方法
- Python:join()方法 list.reverse()
- 2C03-View-Layout-Animation-list-Reverse-Order
- [Leetcode][python]Reverse Linked List/Reverse Linked List II
- post Order Tree traverse - finally AC
- leetcode之Binary Tree Level Order Traverse
- 【LeetCode with Python】 Reverse Linked List II
- leetcode [python] 【206】Reverse Linked List
- 206. Reverse Linked List [easy] (Python)
- leedcode(9),Reverse Linked List(python)
- 206. Reverse Linked List(python)
- 剑指 offer代码解析——面试题35第一个只出现一次的字符
- C++作业2
- 第一次跳槽之后的生活
- 第二次上机报告2-作业
- 70. Climbing Stairs
- Python Traverse list reverse order
- 将.hhc文件转换成html文件解析
- c++作业2
- JDK源码阅读-1-Collection
- System.err.println()与System.out.println的区别
- Servlet 单例多线程
- java打包jar类库
- 第三周项目4(3)年龄几何
- ListView的优化
reversed()
doesn't modify the list.reversed()
doesn't make a copy of the list (otherwise it would require O(N) additional memory). If you need to modify the list usealist.reverse()
; if you need a copy of the list in reversed order usealist[::-1]
. – J.F. SebastianFeb 9 '09 at 19:27