python學習之切片

來源:互聯網
上載者:User

標籤:fonts   log   color   bsp   har   其他   player   沒有   pre   

  所謂切片,其實是列表的部分元素——Python稱之為切片。要建立切片,可指定要使用的第一個元素和最後一個元素的索引 。

players = [‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]   print(players[0:3])#運行結果[‘charles‘, ‘martina‘, ‘michael‘] 

  如果你沒有指定第一個索引, Python將自動從列表開頭開始:

players = [‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]print(players[:4])#運行結果[‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘] 

  要讓切片終止於列表末尾,也可使用類似的文法。例如,如果要提取從第3個元素到列表末尾的所有元素,可將起始索引指定為2,並省略終止索引。

  負數索引返回離列表末尾相應距離的元素,因此你可以輸出資料行表末尾的任何切片。例如,如果你要輸出名單上的最後三名隊員,可使用切片players[-3:]:

players = [‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘, ‘eli‘]print(players[-3:]) 

  要複製列表,可建立一個包含整個列表的切片,方法是同時省略起始索引和終止索引([ : ])這讓Python建立一個始於第一個元素,終止於最後一個元素的切片,即複製整個列表。

my_foods = [‘pizza‘, ‘falafel‘, ‘carrot cake‘]   friend_foods = my_foods[:]

  元組:

  元組的概念打算一帶而過,因為元組就是一個不能修改的列表,列表定義的時候用的是[]中括弧,而元組則是圓括弧,其他並沒有什麼差異。


 

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.