第三章 操作列表
3.1 遍历整个列表(for循环)
words = ['a', 'b', 'c']
for word in words:
print(word)
输出:a
b
c
其中word是一个变量,可指定任何名称。
3.2 创建数字列表
3.2.1 使用range()函数
for value in range(1, 5):
print(value)
输出:1
2
3
4
3.2.2 使用range()函数创建数字列表
number = list(range(1, 5))
print(number)
输出:[1, 2, 3, 4]
使用range()函数时,还可以指定步长。
number = list(range(1, 5, 2))
print(number)
输出:[2, 4]
range()函数从2开始,每次增加2,直至到达或超过终值5。
3.3 列表解析
squars = [value**2 for value in range(1, 11)]
print(squars)
输出:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
3.4 切片
要创建切片,可以指定要使用的第一个元素的索引和最后一个元素的索引加1。
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:2])
输出: [‘charles’, ‘martina’]
若没有指定第一个索引,python将自动从列表开头开始。
print(players[:3]) #从列表开头开始,打印列表前三个元素
输出: [‘charles’, ‘martina’, ‘michael’]
要让切片终止于列表末尾,也可以不指定后面的索引。
print(players[2:]) # 从索引为2的元素开始到列表末尾
输出: [‘michael’, ‘florence’, ‘eli’]
负数索引返回离列表相应距离的元素。
print(players[-3:]) # 打印列表后三个元素
输出:[‘michael’, ‘florence’, ‘eli’]
3.4.1 遍历切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
for player in players[1:4]:
# (遍历切片)遍历列表索引为1至3的元素
print(player)
3.4.2 复制列表
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引。
players = ['charles', 'martina', 'michael', 'florence', 'eli']
new_players = players[:]
3.5 元组
Python将不能修改的值成为不可变的,而不可变的列表称为元组。
yuanzu = (200, 500) # 元组是由圆括号来标识的
元组的值无法修改,若想改变元组中的值,只能重新定义整个元组。
yuanzu = (200, 500)
yuanzu = (100, 400) # 重新定义元组(修改元组中的值)