slice()
轉載須註明出處:簡書@Orca_J35 | GitHub/">GitHub@ofollow,noindex">orca-j35 ,所有筆記均託管於python_notes 倉庫
相關筆記:『Subscriptions & Slicings.md』
如果需要生成迭代器版本的切片,則可使用
itertools.islice()
方法。
:hammer:class slice(stop )
:hammer:class slice(start ,stop [,step ])
該函式用於建立切片(
slice
)物件,切片物件表示由range(start, stop,step)
指定的索引的集合。
start
,stop
,step
可以是任意型別的值,其中start
和step
的預設值是None
。
slice(6,b'a','b') #> slice(6, b'a', 'b') slice(6) #> slice(None, 6, None)
在使用擴充套件索引語法時,會自動生成切片物件。例如a[start:stop:step]
將被翻譯為a[slice(start,stop,step)]
,並使用None
填充切片中缺少的項,然後將結果傳遞給__getitem__
方法。因此,在使用擴充套件索引語法時,也可直接使用切片物件。
class Cls: def __getitem__(self,key): return key # 使用擴充套件索引語法時,會自動生成切片物件,還會使用None填充空缺項 Cls()[0:1] #> slice(0, 1, None) a = [1,2,3,4,5,6,7,8,9] a[0:7:2] #> [1, 3, 5, 7] # 與直接使用切片物件等效 a[slice(0,7,2)] #> [1, 3, 5, 7]
示例 - 為自定義類實現 subscription 和 slicing:
# 該示例沒有實現負索引,也沒有對切片的step進行處理 class Fib(object): def __getitem__(self, n): # 需要手動判斷實參型別,從而區分subscription和slicing if isinstance(n, int): # n是索引 a, b = 1, 1 for x in range(n): a, b = b, a + b return a if isinstance(n, slice): # n是切片 # 展示如何利用切片物件完成切片操作 start = n.start # 獲取切片的下界 stop = n.stop # 獲取切片的上界 if start is None: start = 0 a, b = 1, 1 L = [] for x in range(stop): if x >= start: L.append(a) a, b = b, a + b return L Fib()[:5] #> [1, 1, 2, 3, 5] # 可直接使用 slice 物件 Fib()[slice(10)] #> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Slice objects
本節涵蓋了The standard type hierarchy -> Slice objects 中的內容。
切片物件用於表示
__getitem__()
方法獲得的切片,也可通過內建函式
slice()
建立切片物件。
切片物件擁有三個特殊只讀屬性:
start stop step
以上三個屬性可以是任意型別的值,並且沒有其他功能,但是 Numerical Python 和其它第三方擴充套件會使用這三個屬性。如果在建立切片物件時,省略了上述某個屬性,則會將其設定為None
。
class Cls: def __getitem__(self,key): return key Cls()[0,b'orca':'_'] #> (0, slice(b'orca', '_', None))
在使用擴充套件索引語法時,會自動生成切片物件。例如a[start:stop:step]
將被翻譯為a[slice(start,stop,step)]
,並使用None
填充切片中缺少的項。在使用擴充套件索引語法時,也可直接使用切片物件。
class Cls: def __getitem__(self,key): return key # 使用擴充套件索引語法時,會自動生成切片物件,還會使用None填充空缺項 Cls()[0:1] #> slice(0, 1, None) a = [1,2,3,4,5,6,7,8,9] a[0:7:2] #> [1, 3, 5, 7] # 直接使用切片物件 a[slice(0,7,2)] #> [1, 3, 5, 7]
切片物件支援一種方法:
-
slice.indices(self ,length )
This method takes a single integer argumentlength and computes information about the slice that the slice object would describe if applied to a sequence oflength items. It returns a tuple of three integers; respectively these are thestart andstop indices and thestep or stride length of the slice. Missing or out-of-bounds indices are handled in a manner consistent with regular slices.
# S.indices(len) -> (start, stop, stride) # 該方法用於計算,將長度為length的序列按照slice物件執行切片時, # 子序列在原序列中的(start, stop, step) slice(3).indices(4) #> (0, 3, 1) slice(3).indices(2) #> (0, 2, 1)
因為slice.__hash__
等於None
,所以當試圖獲取 slice 類的例項的雜湊值時會丟擲異常。