2016年12月27日 星期二

Python List Slice with negative step/stride

More List Slice

這一篇紀錄一下所謂的 Extended Slice 中,假如 step 或 stride 參數是負整數是甚麼意思。

x[i:j:m] 是 list 的定義

x 中的 indices 是等於 i, i + k, i + 2k, i + 3k ... 直到 j,但不包括 j。

假如 i 或 j 是空的或是 None 的話,他們就會是最前和最後的index,而誰是前,誰是後,就是看 k 的正負。

In [1]:
# 先做出一個 list
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [2]:
# step 是 -1,其實就是把整個 list 前後反轉
# 因為用上面的公式, k 是負的,所以 i 是 len(x) , j 是 -(len(x)+1) ‧ 
x[::-1]
Out[2]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
In [3]:
# 因為 step 是負數,所以 j 是 -(len(x)+1)
x[5::-1]
Out[3]:
[5, 4, 3, 2, 1, 0]
In [4]:
# 因為 step 是負數,所以 i 是 len(x)
x[:5:-1]
Out[4]:
[9, 8, 7, 6]
In [5]:
# 因為 step 是負數‧沒辦法從 index 3 反向走去 index 8,所以是空的 list
x[3:8:-1]
Out[5]:
[]
In [6]:
# 因為 step 是負數‧從 index 8 反向走去 index 3
x[8:3:-1]
Out[6]:
[8, 7, 6, 5, 4]


Reference 1: Extended slice that goes to beginning of sequence with negative stride

Reference 2: Explain Python's slice notation

Reference 3: Python Doc

Jupyter(IPython) notebook: Link

沒有留言:

張貼留言