操作列表
遍历列表——for循环
- 最简单
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
输出:
alice
david
carolina
- 更多操作:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ', that was a great trick !')
print("I can't wait to see your next trick, " + magician.title() + '.\n')
代码是否属于循环取决于代码之前的缩进。循环执行完后,继续执行循环下面的代码。
- 循环之后
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ', that was a great trick !')
print("I can't wait to see your next trick, " + magician.title() + '.\n')
print("Thank you, everyone.That was a great magic show.")
数值列表
数字列表的基本操作
- range() 一系列的数字
数列range(1, 5)只表示1,2,3,4。
for value in range(1, 5): # 数列range(1, 5)只表示1,2,3,4.
print(value) # 打印
- list() 与 range() 数字列表
list()可以将一系列数字转变为列表。
numbers = list(range(1, 6))
print(numbers)
- 使用步长
数值不断加2,直到达到或超过终值。
# 指定步长
numbers = list(range(2, 20, 2))
print(numbers)
- range() 的更多应用
创建从11到19的平方的列表:
squares = [] # 创建空列表
numbers = list(range(11, 20))
for number in numbers:
square = number**2 # 临时变量
squares.append(square) # 不断在末尾添加
print(squares)
数字列表的计算
- min() 最小值
- max() 最大值
- sum() 求总和
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(numbers)) # 最小值
print(max(numbers)) # 最大值
print(sum(numbers)) # 总和
列表解析
- 举个栗子
squares = [number**2 for number in range(1, 11)]
print(squares)
慢慢体会~
使用列表的一部分
列表切片
如果指定0-3, 那么只会输出索引为0、1、2的元素。
players = ['charles', 'martina', 'michael', 'florence', 'eli']
# 第一个数字表示开始的索引.第二个数字表示结束的位置(不是索引)
print(players[0:3])
# ['charles', 'martina', 'michael']
print(players[2:4])
# ['michael', 'florence']
# 第一个省略表示自动从头
print(players[:4])
# ['charles', 'martina', 'michael', 'florence']
# 第二个省略表示自动到末尾
print(players[2:])
# ['michael', 'florence', 'eli']
# 用负数表示提取列表最后几个元素的切片.
print(players[-3:]) # ['michael', 'florence', 'eli']
遍历切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("First three:")
for player in players[0:3]:
print(player.title())
输出:
First three:
Charles
Martina
Michael
复制列表
- 不相关的复制
my_foods = ['pizza', 'falafel', 'carrot cake']
# 复制副本,使他们完全不相关
friend_foods = my_foods[:]
证实:
my_foods.append('cannoli')
friend_foods.append('ice cream')
print('my new:')
print(my_foods)
print('friend new:')
print(friend_foods)
他们并没有关联,而是各变各的
- 相关的复制
my_foods = ['pizza', 'falafel', 'carrot cake']
# 复制原形,使他们相互关联
friend_foods = my_foods
my_foods变化, friend_foods也会变化
friend_foods变化, my_food 也会变化
元组
- 定义元组
元组类似列表,列表可以被改变,元组是不可以被改变的。
使用方法与列表一致。
dimensions = (200, 50)
print(dimensions)
print(dimensions[0])
print(dimensions[1])
- 遍历元组中的所有值
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
- 重新定义元组
元组元素虽然不能被改变,但是可以重新定义元组。
dimensions = (200, 50)
dimensions = (400, 100)