基本切片
對於任何可迭代的(例如,字串,列表等),Python 允許你切片並返回其資料的子字串或子列表。
切片格式:
iterable_name[start:stop:step]
哪裡,
start
是切片的第一個索引。預設為 0(第一個元素的索引)stop
超過切片的最後一個索引。預設為 len(可迭代)step
是步長(下面的例子更好地解釋)
例子:
a = "abcdef"
a # "abcdef"
# Same as a[:] or a[::] since it uses the defaults for all three indices
a[-1] # "f"
a[:] # "abcdef"
a[::] # "abcdef"
a[3:] # "def" (from index 3, to end(defaults to size of iterable))
a[:4] # "abcd" (from beginning(default 0) to position 4 (excluded))
a[2:4] # "cd" (from position 2, to position 4 (excluded))
此外,以上任何一種都可以與定義的步長一起使用:
a[::2] # "ace" (every 2nd element)
a[1:4:2] # "bd" (from index 1, to index 4 (excluded), every 2nd element)
指數可以是負數,在這種情況下,它們是從序列的末尾計算出來的
a[:-1] # "abcde" (from index 0 (default), to the second last element (last element - 1))
a[:-2] # "abcd" (from index 0 (default), to the third last element (last element -2))
a[-1:] # "f" (from the last element to the end (default len())
步長也可以是負數,在這種情況下,切片將以相反的順序遍歷列表:
a[3:1:-1] # "dc" (from index 2 to None (default), in reverse order)
此構造對於反轉可迭代非常有用
a[::-1] # "fedcba" (from last element (default len()-1), to first, in reverse order(-1))
請注意,對於否定步驟,預設 end_index
是 None
(請參閱 http://stackoverflow.com/a/12521981 )
a[5:None:-1] # "fedcba" (this is equivalent to a[::-1])
a[5:0:-1] # "fedcb" (from the last element (index 5) to second element (index 1)