【Python】切片

來源:互聯網
上載者:User

標籤:副本   add   back   get   ble   切片   new   nan   tom   

處理Python的部分元素,稱之為切片。

建立切片

指定要是用的第一個元素和最後一個元素的索引,與range()函數一樣,Python在到達你指定的第二個索引前面的元素後停止。

先定義一個列表vegetables

vegetables = [‘tomato‘,‘bean‘,‘potato‘,‘onion‘,‘radish‘]

取出第1~3個元素

print(vegetables[0:3])

取出第2~4個元素

print(vegetables[1:4])

取出前4個元素

print(vegetables[:4])

取出第2個元素後的所有元素(包含第2個)

print(vegetables[2:])

取出最後三個元素

print(vegetables[-3:])
複製列表

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

fruits = [‘aplle‘,‘pear‘,‘lemon‘,‘peach‘]fruits_copy = fruits[:]print(fruitsfoot_copy)

可能從上述案例中我們還沒辦法看出是有2個列表,下面整個例子可以更好的說明

fruits = [‘aplle‘,‘pear‘,‘lemon‘,‘peach‘]fruits_copy = fruits[:]fruits.append(‘grape‘)fruits_copy.append(‘banana‘)print(fruits)print(fruits_copy)

列印結果:

[‘aplle‘, ‘pear‘, ‘lemon‘, ‘peach‘, ‘grape‘]
[‘aplle‘, ‘pear‘, ‘lemon‘, ‘peach‘, ‘banana‘]

這就說明了確實是複製了列表。

以下是一個錯誤的案例

fruits = [‘aplle‘,‘pear‘,‘lemon‘,‘peach‘]fruits_copy = fruits
fruits.append(‘grape‘)fruits_copy.append(‘banana‘)print(fruits)print(fruits_copy)

列印結果:

[‘aplle‘, ‘pear‘, ‘lemon‘, ‘peach‘, ‘grape‘, ‘banana‘]
[‘aplle‘, ‘pear‘, ‘lemon‘, ‘peach‘, ‘grape‘, ‘banana‘]

這裡將fruits賦給fruits_copy,而不是將fruits的副本儲存到fruits_copy.

【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.