Python中使用列表的一部分——参考Python编程从入门到实践
程序员文章站
2022-06-29 08:22:35
处理列表中的部分元素——切片 1. 切片 2. 遍历切片 3. 复制列表 My favorite foods are:['pizza', 'falafel', 'carrot cake'] My friend's favorite foods are:['pizza', 'falafel', 'ca ......
处理列表中的部分元素——切片
1. 切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) # 打印列表的切片,其中包含前三个元素,输出也是一个列表
print(players[1:4]) # 提取列表的第2、3、4个元素
print(players[:4]) # 没有指定索引,故打印出列表的前4个元素
print(players[2:]) # 没有指定终止索引,故打印出列表中第二个元素之后的所有元素(不包含第二个,由于索引从0开始)
print(players[-3:]) # 列表从右往左的索引从-1开始,故打印出列表的最后三个元素
print(players[:-2]) # 切片时不包含指定的第二个索引,故打印除了最后两个元素以外的其他元素
运行结果:
['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
['charles', 'martina', 'michael']
2. 遍历切片
for player in players[:3]: # 遍历前3个元素
print(player.title())
运行结果:
charles
martina
michael
3. 复制列表
my_foods = ['pizza', 'falafel', 'carrot cake'] # 定义列表
friend_foods = my_foods[:] # 复制列表
print('my favorite foods are:')
print(my_foods)
print("\nmy friend's favorite foods are:")
print(friend_foods)
运行结果:
my favorite foods are:
['pizza', 'falafel', 'carrot cake']
['pizza', 'falafel', 'carrot cake']
my friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']
['pizza', 'falafel', 'carrot cake']
为每个列表添加一个元素:
my_foods.append('cannoli')
friend_foods.append('ice cream')
print('my favorite foods are:')
print(my_foods)
print("\nmy friend's favorite foods are:")
print(friend_foods)
运行结果:
my favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']
['pizza', 'falafel', 'carrot cake', 'cannoli']
my friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
['pizza', 'falafel', 'carrot cake', 'ice cream']
若将复制列表代码friend_foods = my_foods[:]用friend_foods = my_foods替代,运行上边添加元素代码会怎么呢?
my favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'cannoli', 'ice cream']
['pizza', 'falafel', 'carrot cake', 'cannoli', 'cannoli', 'ice cream']
my friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'cannoli', 'ice cream']
['pizza', 'falafel', 'carrot cake', 'cannoli', 'cannoli', 'ice cream']
比较运行结果可知:代码friend_foods = my_foods只是将两个变量指向同一个列表;
代码friend_foods = my_foods[:]是完全复制了一个列表,得到两个独立的列表
note:复制列表时有么有方括号将会得到两种不同的结果。