1、创建切片,可指定要使用的第一个元素的索引和最后一个元素的索引加1。
players = ['charles','martina','michael','florence','eli']
print (players[0:3])
结果:['charles','martina','michael']
如果没有指定第一个索引,Python将自动从列表头开始:
players = ['charles','martina','michael','florence','eli']
print (players[:4])
结果:['charles','martina','michael','florence']
如果没有指定第二个个索引,Python将自动到列表末尾:
players = ['charles','martina','michael','florence','eli']
print[2:]
结果:['michael','florence','eli']
利用负号切片:
players = ['charles','martina','michael','florence','eli']
print[-4:-1]
结果:['martina','michael','florence']
遍历切片:
players = ['charles','martina','michael','florence','eli']
for player in players [:3]:
print(player.title())
结果:
Charles
Martina
Michael
复制列表:
my_num = [1,2,3,4]
friend_num = my_num[:]
my_num.append('5')
friend_num.append('6')
print(my_num ) 结果:[1,2,3,4,5]
print(friend_num ) 结果:[1,2,3,4,6]
事实证明friend_num和my_num是两个列表,倘若我们只是简单地将my_num赋值给friend_num就不能得到两个列表
friend_num = my_num
my_num.append('5')
friend_num.append('6')
print(my_num) 结果:[1,2,3,4,6]