python中使用序列的方法

來源:互聯網
上載者:User
本文執行個體講述了python中使用序列的方法。分享給大家供大家參考。具體如下:

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

#!/usr/bin/python# Filename: seq.pyshoplist = ['apple', 'mango', 'carrot', 'banana']# Indexing or 'Subscription' operationprint '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 listprint '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 stringname = '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 appleItem 1 is mangoItem 2 is carrotItem 3 is bananaItem -1 is bananaItem -2 is carrotItem 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 wacharacters 2 to end is aroopcharacters 1 to -1 is waroocharacters 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解譯器互動地嘗試不同切片指定組合,即在提示符下你能夠馬上看到結果。序列的神奇之處在於你可以用相同的方法訪問元組、列表和字串。

希望本文所述對大家的Python程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.