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.
本文介绍了在Python中如何逆序遍历列表的方法,包括使用内置函数reversed、切片[::-1]、range函数结合负步长、自定义生成器等技巧,并探讨了这些方法的优缺点。
|
252
50
| |
|
add a comment
|
|
412
|
Use the
To also access the original index:
| |||
|
61
|
You can do:
(Or whatever you want to do in the for loop.) The | ||||||||||||||||
|
|
32
|
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.
| ||||||||||||||||||||
|
|
15
|
It 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 Fyi, the | ||||||||||||
|
|
10
|
The
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:
This one avoids creating a copy of the sequence. Obviously, the | ||
|
2
|
How about without recreating a new list, you can do by indexing:
OR
| ||
|
1
|
Use | |||
|
1
|
The other answers are good, but if you want to do as List comprehension style
| ||
|
1
|
| |||
|
1
|
OR
|
您可能感兴趣的与本文相关的镜像
Python3.9
Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本
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. Sebastian Feb 9 '09 at 19:27