Python 学习笔记(五)——切片

处理列表中部分元素——切片 区间同 range() 仍然是左闭右开[m, n) 可以记忆为元素总个数为 n-m

切片

1
2
players = ['charles', 'martina', 'michael', 'eli']
print(players[0:3]) # 3-0=3 个

注意 如果没有指定第一个索引,自动从表头开始

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

欲将切片终止于末尾,可以使用上面类似的方法[m:]

1
2
players = ['charles', 'martina', 'florence', 'michael', 'eli']
print(players[0:])

遍历切片

1
2
3
players = ['charles', 'martina', 'florence', 'michael', 'eli']
for player in players[1:]:
print(player.title())

结果:

1
2
3
4
Martina
Florence
Michael
Eli

———— The End ————