深入探討Python序列神奇之處
在Python編程語言這樣一款功能強(qiáng)大的面向?qū)ο笮陀?jì)算機(jī)通用語言中,有很多使用方法都和那些常見的額編程語言有很大的不同之處,比如今天為大家介紹的Python序列就是其中一個。首先,我們來學(xué)習(xí)如何使用索引來取得序列中的單個項(xiàng)目。這也被稱作是下標(biāo)操作。每當(dāng)你用方括號中的一個數(shù)來指定一個Python序列的時(shí)候,Python會為你抓取序列中對應(yīng)位置的項(xiàng)目。記住,Python從0開始計(jì)數(shù)。因此,shoplist[0]抓取第一個項(xiàng)目,shoplist[3]抓取shoplist序列中的第四個元素。#t#
索引同樣可以是負(fù)數(shù),在那樣的情況下,位置是從序列尾開始計(jì)算的。因此,shoplist[-1]表示序列的最后一個元素而shoplist[-2]抓取序列的倒數(shù)第二個項(xiàng)目。
切片操作符是Python序列名后跟一個方括號,方括號中有一對可選的數(shù)字,并用冒號分割。注意這與你使用的索引操作符十分相似。記住數(shù)是可選的,而冒號是必須的。
切片操作符中的第一個數(shù)(冒號之前)表示切片開始的位置,第二個數(shù)(冒號之后)表示切片到哪里結(jié)束。如果不指定第一個數(shù),Python就從序列首開始。如果沒有指定第二個數(shù),則Python會停止在序列尾。注意,返回的序列從開始位置 開始 ,剛好在 結(jié)束 位置之前結(jié)束。即開始位置是包含在序列切片中的,而結(jié)束位置被排斥在切片外。
這樣,shoplist[1:3]返回從位置1開始,包括位置2,但是停止在位置3的一個序列切片,因此返回一個含有兩個項(xiàng)目的切片。類似地,shoplist[:]返回整個序列的拷貝。
你可以用負(fù)數(shù)做切片。負(fù)數(shù)用在從序列尾開始計(jì)算的位置。例如,shoplist[:-1]會返回除了最后一個項(xiàng)目外包含所有項(xiàng)目的序列切片。
使用Python解釋器交互地嘗試不同切片指定組合,即在提示符下你能夠馬上看到結(jié)果。Python序列的神奇之處在于你可以用相同的方法訪問元組、列表和字符串。
- 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序列的全部內(nèi)容。















 
 
 



 
 
 
 