第四章_操作列表
4.1 遍历整个列表
任务:把魔术师名单中的每个名字打印出来
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician)
alice
david
carolina
注意
-
magician 与 magicians 区别,列表元素 v.s. 列表,单数 v.s. 复数
-
编写for循环时,可以给依次与列表中每个值关联的临时变量指定任意名称
-
选择描述单个列表元素的有意义的名称大有裨益
for cat in cats
for dog in dogs
for item in item_list
4.1.2 在for循环中(缩进)执行更多操作
任务:对每位魔术师,打印一条消息,指出他的表演太精彩了
方法:使用for循环+f字符串+title()
注意: for循环中(缩进)可以包含多行代码,针对列表中的每个值都执行一遍
magicians = ['alice','david','carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!
magicians = ['alice','david','carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}. \n")
Alice, that was a great trick!
I can't wait to see your next trick, Alice.
David, that was a great trick!
I can't wait to see your next trick, David.
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
4.1.3 在for循环结束后(不缩进)执行一些操作
注意: for循环后(没有缩进)的代码只执行一次,不会重复执行
任务:在给每个魔术师的消息后再打印一条消息,向全体魔术师致敬,感谢他们的精彩表演
magicians = ['alice','david','carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}. \n")
print("Thank you, everyone. That was a great magic show!")
Alice, that was a great trick!
I can't wait to see your next trick, Alice.
David, that was a great trick!
I can't wait to see your next trick, David.
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
Thank you, everyone. That was a great magic show!
4.2 避免错误缩进
-
其他程序设计语言(如Java或者C)采取括号“{}”分隔代码块,Python采用代码缩进和冒号“:”区分代码之间的层次
-
Python是使用缩进和冒号“:”来区分不同的代码块,所以对缩进有严格要求
-
缩进可以使用空格键或者 < Tab > 键实现。使用空格键时,通常情况下采用4个空格作为一个缩进量,而使用< Tab >键时,则采用一个< Tab >键作为一个缩进量
-
通常情况下建议采用空格进行缩进
4.2.1 忘记缩进
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician)
File "<ipython-input-6-ca8d82b477e3>", line 3
print(magician)
^
IndentationError: expected an indented block
4.2.2 忘记缩进额外的代码行
magicians = ['alice','david','carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}. \n")
Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
4.2.3 不必要的缩进
massege = "Hello Python World!"
print(massege)
File "<ipython-input-8-4938d5d5ac94>", line 2
print(massege)
^
IndentationError: unexpected indent
4.2.4 循环后不必要的缩进
magicians = ['alice','david','carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}. \n")
print("Thank you, everyone. That was a great magic show!")
Alice, that was a great trick!
I can't wait to see your next trick, Alice.
Thank you, everyone. That was a great magic show!
David, that was a great trick!
I can't wait to see your next trick, David.
Thank you, everyone. That was a great magic show!
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
Thank you, everyone. That was a great magic show!
4.2.5 遗漏了冒号
magicians = ['alice','david','carolina']
for magician in magicians
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}. \n")
File "<ipython-input-10-5dc11a10cf91>", line 2
for magician in magicians
^
SyntaxError: invalid syntax
4.3 创建数值列表
4.3.1 range()和list()
-
range(): 创建数字序列
range(start, stop, step):
start:可选,整数,指定从哪个位置开始,默认为 0。
stop:可选,整数,指定在哪个位置结束。
step:可选,整数,指定增量。默认为 1。 -
list():将range()的结果直接转换为列表
for value in range(1,5):
print(value)
# 输出不包含5
1
2
3
4
for value in range(5):
print(value)
0
1
2
3
4
for value in range(1,10,2):
print(value)
1
3
5
7
9
list(range(1,5))
[1, 2, 3, 4]
4.3.2 使用range()创建数字列表
任务: 打印1-10的偶数,步长为2
even_numbers = list(range(2,11,2))
print(even_numbers)
[2, 4, 6, 8, 10]
任务: 创建一个列表,包含1 - 10的平方
squares = []
for value in range(1,11):
square = value ** 2
squares.append(square)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
4.3.3 对数字列表执行简单的统计计算
- min():最小债
- max():最大值
- sum():求和
digits = list(range(1,11))
print(digits)
print(min(digits))
print(max(digits))
print(sum(digits))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1
10
55
4.3.4 列表解析
- 列表解析(list comprehension)提供了一种优雅的生成列表的方法,能用一行代码代替十几行代码,而且不损失任何可读性。而且,性能还快很多很多。
squares = []
for value in range(1,11):
squares.append(value ** 2)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares = [value ** 2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print([value ** 2 for value in range(1,11)])
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print('\n'.join([' '.join(["%2s x%2s = %2s"%(j,i,i*j) for j in range(1,i+1)]) for i in range(1,10)]))
1 x 1 = 1
1 x 2 = 2 2 x 2 = 4
1 x 3 = 3 2 x 3 = 6 3 x 3 = 9
1 x 4 = 4 2 x 4 = 8 3 x 4 = 12 4 x 4 = 16
1 x 5 = 5 2 x 5 = 10 3 x 5 = 15 4 x 5 = 20 5 x 5 = 25
1 x 6 = 6 2 x 6 = 12 3 x 6 = 18 4 x 6 = 24 5 x 6 = 30 6 x 6 = 36
1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35 6 x 7 = 42 7 x 7 = 49
1 x 8 = 8 2 x 8 = 16 3 x 8 = 24 4 x 8 = 32 5 x 8 = 40 6 x 8 = 48 7 x 8 = 56 8 x 8 = 64
1 x 9 = 9 2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 5 x 9 = 45 6 x 9 = 54 7 x 9 = 63 8 x 9 = 72 9 x 9 = 81
print('\n'.join([' '.join(["%2s x%2s = %2s"%(j,i,i*j) for j in range(1,i+1)]) for i in range(1,10)]))
print('\n'.join([''.join([('python'[(x-y) % len('python')] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0else' ') for x in range(-30, 30)]) for y in range(15, -15, -1)]))
4.4 使用列表的一部分
4.4.1 切片
指定要使用的第一个元素和最后一个元素的索引
players = ['charles','matina','michael','florence','eli']
print(players[0:3])
['charles', 'matina', 'michael']
#没有指定起始索引,自动从列表开头开始
players = ['charles','matina','michael','florence','eli']
print(players[:3])
['charles', 'matina', 'michael']
#没有指定终止索引,自动到列表末尾结束
players = ['charles','matina','michael','florence','eli']
print(players[1:])
['matina', 'michael', 'florence', 'eli']
#负数索引
players = ['charles','matina','michael','florence','eli']
print(players[-3:])
['michael', 'florence', 'eli']
#负数索引
players = ['charles','matina','michael','florence','eli']
print(players[0:4:2])
['charles', 'michael']
4.4.2 遍历切片
任务: 打印以下结果
Here are the first three players on my team:
Charles
Matina
Michael
players = ['charles','matina','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:
Charles
Matina
Michael
4.4.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']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
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']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods #赋值与复制的区别
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', 'ice cream']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
4.5 元组 (tuple)
- 不能修改的值称为不可变的
- 不可变的列表称为元组
- 列表:[ ]
- 元组:( )
- 相比于列表,元组是更简单的数据结构
- 如果需要存储一组在整个程序生命周期内都不变的值,可以用元组
4.5.1 定义元组
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
200
50
# 元组中的值不能修改
dimensions = (200,50)
dimensions[0] = 250
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-e6d9c4c4b557> in <module>
1 dimensions = (200,50)
----> 2 dimensions[0] = 250
TypeError: 'tuple' object does not support item assignment
4.5.2 遍历元组
dimensions = (200,50)
for dimension in dimensions:
print(dimension)
200
50
4.5.3 修改元组变量
元组的元素不能修改,但可以给存储元组的变量赋值来重新定义整个元组
dimensions = (200,50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400,100)
print("\nOriginal dimensions:")
for dimension in dimensions:
print(dimension)
Original dimensions:
200
50
Original dimensions:
400
100
4.6 设置代码格式
- 缩进:建议用4个空格而不是Tab
- 行长
- 空行
- ……
练习
- 使用一个 for 循环打印数 1~20(含)
- 一百万求和: 创建一个包含数 1~1 000 000 的列表,再使用 min()和 max()核实该列表确实是从 1 开始、 到 100000 结束的。另外,对这个列表调用函数 sum(),看看 Python 将一百万个数相加需要多长时间
- 立方将同一个数乘三次称为立方。例如,在 Python 中, 2 的立方用 2**3 表示。
- 请创建一个列表,其中包含前 10 个整数(即 1~10)的立方,再使用一个 for 循环将这些立方数都打印出来。
- 使用列表解析实现以上功能