处理列表的部分元素
1.切片
要创建切片,可指定要使用的第一个元素的索引和最后一个元素的索引+1。与函数range()一样。 例如:
players = ['a', 'b', 'c', 'd', 'e']
print(players[0:3])
打印结果如下:
['a','b','c']
如果你要提取列表的第2~4个元素,可将起始索引指定 为1,并将终止索引指定为4:
players = ['a', 'b', 'c', 'd', 'e']
print(players[1:4])
打印结果如下:
['b','c','d']
如果你没有指定第一个索引,Python将自动从列表开头开始:
players = ['a', 'b', 'c', 'd', 'e']
print(players[:4])
打印结果如下:
['a','b','c','d']
如果要提取从第3个元素到列表末尾的所有元素,可将起始索引指定为2,并省略终止索引:
players = ['a', 'b', 'c', 'd', 'e']
print(players[2:])
打印结果如下:
['c','d','e']
如果你要输出名单上的最后三个元素,可使用切片players[-3:]:
players = ['a', 'b', 'c', 'd', 'e']
print(players[-3:])
打印结果如下:
['c','d','e']
2.遍历切片
如果要遍历列表的部分元素,可在for循环中使用切片。 例如:
players = ['a', 'b', 'c', 'd', 'e']
print("遍历前三个元素:")
for player in players[:3]:
print(player.title())
打印结果如下:
A
B
C
3.复制列表
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])。这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。 例如:
my_foods = ['pizza', 'falafel', 'cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("My friend's favorite foods are:")
print(friend_foods)
打印列表后,我们发现他们包含的结果一样,打印结果如下:
My favorite foods are:
['pizza', 'falafel', 'cake']
My friend's favorite foods are:
['pizza', 'falafel', 'cake']
我们在列表中添加一个元素,并核实每个列表:
my_foods = ['pizza', 'falafel', 'cake']
friend_foods = my_foods[:]
my_foods.append('tea')
friend_foods.append('suger')
print("My favorite foods are:")
print(my_foods)
print("My friend's favorite foods are:")
print(friend_foods)
打印列表后,我们发现他们包含的结果不一样,打印结果如下:
My favorite foods are:
['pizza', 'falafel', 'cake', 'tea']
My friend's favorite foods are:
['pizza', 'falafel', 'cake', 'suger']
注意:这里的friend_foods = my_foods[:]不能写成friend_foods = my_foods,不然这两个变量指同一个列表。