標籤:副本 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】切片