熱線電話:13121318867

登錄
首頁精彩閱讀python中使用序列的方法
python中使用序列的方法
2017-08-09
收藏

python中使用序列的方法

本文實例講述了python中使用序列的方法。分享給大家供大家參考。具體如下:

列表、元組和字符串都是序列,但是序列是什么,它們為什么如此特別呢?序列的兩個主要特點是索引操作符和切片操作符。索引操作符讓我們可以從序列中抓取一個特定項目。切片操作符讓我們能夠獲取序列的一個切片,即一部分序列。

#!/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[:]

輸出:    
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解釋器交互地嘗試不同切片指定組合,即在提示符下你能夠馬上看到結果。序列的神奇之處在于你可以用相同的方法訪問元組、列表和字符串。



數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢