python學習筆記 列表的切片

Deuterium_suika發表於2019-03-21

切片

-A slicing selects a range of items in a sequence object (e.g., a string, tuple or list). Slicings may be used as expressions or as targets in assignment or del statements.

  1. 簡單切片

s[begin : end]

begin和end均可以為負值。-1是序列s最後一個元素的索引,-2是倒數第二個元素的索引,以此類推。

2.擴充套件切片

s[begin : end : stride]

當stride引數為正值時,從左至右訪問源序列s的元素;當stride引數為負值時,從右至左訪問源序列s的元素.

spam = ['cat', 'dog', 'bat', 'mouse', 'fish']
print(spam[-3:-1])
print(spam[:4])
print(spam[:-1])
print(spam[-3:])
print(spam[2:])
print(spam[: : -1])
print(spam[1:3:-1])
print(spam[3:1:-1])
複製程式碼

輸出 ['bat', 'mouse']

['cat', 'dog', 'bat', 'mouse']

['cat', 'dog', 'bat', 'mouse']

['bat', 'mouse', 'fish']

['bat', 'mouse', 'fish']

['fish', 'mouse', 'bat', 'dog', 'cat']

[]#逆向訪問[1:3]之間無元素,返回空

['mouse', 'bat']#逆向訪問[3:1]3為閉,1為開,訪問不到'dog'

相關文章