1. 程式人生 > >python:從後往前遍歷列表

python:從後往前遍歷列表

C語言中從後往前遍歷陣列是很方便的,如:

for(int i = 5; i >= 0; i--){
    printf("%d\n", i);
}

但是在python中預設是從前往後遍歷列表的,有時候需要從後往前遍歷。根據 range 函式的用法:

range(start, end[, step])

python中從後往前遍歷列表的方法為:

lists = [0, 1, 2, 3, 4, 5]
# 輸出 5, 4, 3, 2, 1, 0
for i in range(5, -1, -1):
    print(lists[i])

# 輸出5, 4, 3
for i in range(5, 2, -1):
    print(lists[i])