players = ['charies','martina','michael','florence','eli'] print(players[0:3])
['charies', 'martina', 'michael']
该代码打印该列表的一个切片,其中包含三名队员。输出也是一个列表。倘若没有指定第一个索引,Python将自动从列表开头开始。
print(players[:3])
['charies', 'martina', 'michael']
print(players[1:])
['martina', 'michael', 'florence', 'eli']遍历切片
如果要遍历列表的部分元素,可在for循环中使用切片。
players = ['charies','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: Charies Martina Michael复制列表
下面来介绍复制链表的原理。我们要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引[:]。这让python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。
my_foods = ['pizza','apple','cake','water']
friend_foods = my_foods[:]
print("My favorite foods are :")
print(my_foods)
print("My friends' favorite foods are :")
print(friend_foods)
My favorite foods are : ['pizza', 'apple', 'cake', 'water'] My friends' favorite foods are : ['pizza', 'apple', 'cake', 'water']
my_foods = ['pizza','apple','cake','water']
friend_foods = my_foods[:]
friend_foods.append('cannoli')#添加一个新的元素
print("My favorite foods are :")
print(my_foods)
print("My friends' favorite foods are :")
print(friend_foods)
My favorite foods are : ['pizza', 'apple', 'cake', 'water'] My friends' favorite foods are : ['pizza', 'apple', 'cake', 'water', 'cannoli']
friend_foods = my_foods[:]是复制列表,但是如果我们friend_foods = my_foods便不会得到两个列表,这两个变量都指向同一个列表。
元组元组看起来犹如列表,但使用圆括号而不是方括号来标记。定义元组后,就可以使用索引来访问其中的元素,就像访问列表元素一样。但是我们要注意的是元组中的内容定义之后是不可以改变的。
dimension = (200,50) print(dimension[0]) print(dimension[1])
200 50
当我们要修改元组的中的元素时候,python会提示一串错误告诉我们是不可以修改的。
遍历元组中所有值像列表一样,也可以用for循环来遍历元组中的所有值
dimensions = (200,50)
for dimension in dimensions:
print(dimension)
200 50
当我们想要修改元组中的变量的时候,此时只需要重新再进行一次定义即可。



