列表、元組和字符串都是序列,但是序列是什么,它們為什么如此特別呢?序列的兩個主要特
點是索引操作符和切片操作符。索引操作符讓我們可以從序列中抓取一個特定項目。切片操作
符讓我們能夠獲取序列的一個切片,即一部分序列。
#!/usr/bin/python
# Filename: seq.py
shoplist = ['apple', 'mango', 'carrot', 'banana']
# Indexing or 'Subscription' operation
print 'Item 0 is', shoplist[0]
print 'Item 1 is', shoplist[1]
print 'Item 2 is', shoplist[2]
print 'Item 3 is', shoplist[3]
print 'Item -1 is', shoplist[-1]
print 'Item -2 is', shoplist[-2]
# Slicing on a list
print 'Item 1 to 3 is', shoplist[1:3]
print 'Item 2 to end is', shoplist[2:]
print 'Item 1 to -1 is', shoplist[1:-1]
print 'Item start to end is', shoplist[:]
# Slicing on a string
name = 'swaroop'
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]
輸出$ python seq.py
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop
它如何工作首先,我們來學習如何使用索引來取得序列中的單個項目。這也被稱作是下標操作。每當你用
方括號中的一個數來指定一個序列的時候,Python會為你抓取序列中對應位置的項目。記住,
Python從0開始計數。因此,shoplist[0]抓取第一個項目,shoplist[3]抓取shoplist序列中的第四個
元素。
索引同樣可以是負數,在那樣的情況下,位置是從序列尾開始計算的。因此,shoplist[-1]表示
序列的最后一個元素而shoplist[-2]抓取序列的倒數第二個項目。
切片操作符是序列名后跟一個方括號,方括號中有一對可選的數字,并用冒號分割。注意這與
你使用的索引操作符十分相似。
記住數是可選的,而冒號是必須的。切片操作符中的第一個數(冒號之前)表示切片開始的位置,第二個數(冒號之后)表示切片
到哪里結束。如果不指定第一個數,Python就從序列首開始。如果沒有指定第二個數,則
Python會停止在序列尾。注意,返回的序列從開始位置 開始 ,剛好在 結束 位置之前結束。即
開始位置是包含在序列切片中的,而結束位置被排斥在切片外。
這樣,shoplist[1:3]返回從位置1開始,包括位置2,但是停止在位置3的一個序列切片,因此返
回一個含有兩個項目的切片。類似地,shoplist[:]返回整個序列的拷貝。
你可以用負數做切片。負數用在從序列尾開始計算的位置。例如,shoplist[:-1]會返回除了最后
一個項目外包含所有項目的序列切片。
使用Python解釋器交互地嘗試不同切片指定組合,即在提示符下你能夠馬上看到結果。序列的
神奇之處在于你可以用相同的方法訪問元組、列表和字符串。