1.切片
處理列表的部分元素---Python稱之爲切片。要創建切片,可指定要使用的第一個元素和最後一個元素的索引,與函數range()一樣,Python切片在到達指定的第二個索引前的元素後停止。要輸出列表的前三個元素,需要指定索引0-3,這將分別輸出爲0,1,2的元素。
players = ['charles','martina','michael','florence','eli']
print (players[0:3])
輸出結果:
['charles', 'martina', 'michael']
如果沒有指定起始索引,Python從列表的開頭開始提取
print(players[:4])
要讓切片終止於列表末尾,使用如下寫法:
print(players[2:])
負數索引返回離列表末尾相應距離的元素,因此可以輸出列表末尾的任何切片
print(players[-3:])
2.遍歷切片
如果要遍歷列表的部分元素,可以在for循環中使用切片。
遍歷列表中前三名成員,並打印他們的名字如下:
players = ['charles','martina','michael','florence','eli']
print ("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
輸出結果
Here are the first three players on my team:
Charles
Martina
Michael
3.複製列表
要複製列表,可創建一個包含整個列表的切片,方法是同時省略起始索引和終止索引([:]),例:
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
print ("My favorite foods are:")
print (my_foods)
print ("\nMy friend's favorite foods are:")
print (friend_foods)
輸出結果:
My favorite foods are:
['pizza', 'falafel', 'carrot cake']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']