1、切片
要创建切片,可指定要使用的第一个元素和最后一个元素索引
players=['charles','martina','michael','florence','eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])
注意中间是冒号
没有起始索引,python从列表开头开始提取
没有终止索引,python一直提取到最后一个元素
起始索引若为-3,则提取最后三个元素
['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
2、遍历切片
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
4、复制列表
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引[:]
#复制列表
my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods[:]
#核实确实有两个列表
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favourite foods are:")
print(my_foods)
print("\nMy friend's favourite foods are:")
print(friend_foods)
输出
My favourite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']
My friend's favourite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
倘若我们只是简单地将my_foods赋值给friend_foods,就不能得到两个列表