【Python基礎】列表的切片與遍歷

本文標識 : P00011

本文編輯 : 採藥 編程工具 : Python 閱讀時長 : 3分鐘


前言

切片:在python中處理列表的部分元素。

本章我們就來看以下如何"盤"一個列表。

切片

創建切片,我們需要指定使用的第一個元素和最後一個元素的索引。與range()函數一樣,python在到達你指定的第二個索引前面的元素停止。

示例

players = ['charles','martina','michae','florence','eli']  print(players[0:3])

該程式碼的第二行,意思是列印players列表的一個切片,其中只包含3個成員,輸出也是一個列表:

['charles', 'martina', 'michae']

我們可以生成列表的任何子集,比如提取列表的第2-4個元素:

players = ['charles','martina','michae','florence','eli']  print(players[1:4])

輸出結果:

['martina', 'michae', 'florence']

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

players = ['charles','martina','michae','florence','eli']  print(players[:4])

輸出結果:

['charles', 'martina', 'michae', 'florence']

如需要終止於末尾,也可以使用類似的語法:

players = ['charles','martina','michae','florence','eli']  print(players[2:])

輸出結果:

['michae', 'florence', 'eli']

無論列表有多長,這種語法都能夠輸出從特定位置到列表末尾的所有元素,比如輸出列表players,可以使用切片players[-3:]:

players = ['charles','martina','michae','florence','eli']  print(players[-3:])

輸出結果:

['michae', 'florence', 'eli']

遍歷切片

如需遍歷列表的部分元素,可在for循環中使用切片:

players = ['charles','martina','michae','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:  Michae  Florence  Eli

第三行程式碼意思是,只遍歷最後三名的成員,而沒有全部遍歷。

複製列表

複製列表,可創建一個包含整個列表的切片,可以同時省略開始索引和終止索引([:]).

players = ['charles','martina','michae','florence','eli']  famous_players = players[:]  print(players)  print(famous_players)

輸出結果:

['charles', 'martina', 'michae', 'florence', 'eli']  ['charles', 'martina', 'michae', 'florence', 'eli']

為了驗證我們確實是有兩個列表,我們分別給兩個列表添加不同的成員,進行驗證:

players = ['charles','martina','michae','florence','eli']  famous_players = players[:]  players.append('bob')  famous_players.append('tom')  print(players)  print(famous_players)

輸出結果:

['charles', 'martina', 'michae', 'florence', 'eli', 'bob']  ['charles', 'martina', 'michae', 'florence', 'eli', 'tom']