第四章 操作列表
4.1 遍历整个列表
In [1]:
# 通过使用for循环
In [2]:
magicians = ['laura', 'andrew', 'sarah']
for magician in magicians:
print(magician)
laura
andrew
sarah
In [3]:
# 循环:循环这种概念很重要,因为它是让计算机自动完成重复工作的常见方式之一。
In [4]:
# eg.在上述例子中,python首先读取代码行“for magician in magicians:”,
# 然后获取列表“magicians”中的第一个值'laura',并将其与变量magician相关联, # tips:【列表】/【值】/【变量】
# 然后读取下一行代码“print(magician)” →→打印出laura;
# 然后返回到循环的第一行“for magician in magicians:”,获取下一个值andrew,并将其与变量magician相关联,然后读取下一行代码print,打印第二个值andrew;(即循环上述几个步骤)
# 以此类推,循环上述几个步骤。
In [5]:
# 编写for循环时,可以给依次与列表中每个值相关联的临时变量指定任意名称。然而选择描述单个列表元素的有意义名称大有裨益。
# eg.for cat in cats:
# eg.for item in list_of_items:
In [6]:
magicians = ['laura', 'andrew', 'sarah']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
Laura, that was a great trick!
Andrew, that was a great trick!
Sarah, that was a great trick!
In [7]:
# tips:一定要记得print,不print就没有显示,所以需要print的都在print括号里。
In [8]:
magicians = ['laura', 'andrew', 'sarah']
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")
Laura, that was a great trick!
I can't wait to see your next trick, Laura.
Andrew, that was a great trick!
I can't wait to see your next trick, Andrew.
Sarah, that was a great trick!
I can't wait to see your next trick, Sarah.
In [9]:
# tips:两个函数调用print时都缩进了
In [10]:
magicians = ['laura', 'andrew', 'sarah']
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.")
Laura, that was a great trick!
I can't wait to see your next trick, Laura.
Andrew, that was a great trick!
I can't wait to see your next trick, Andrew.
Sarah, that was a great trick!
I can't wait to see your next trick, Sarah.
Thank you,everyone.
In [11]:
# for循环:for循环处理数据:
# eg.可以使用for循环来初始化游戏;遍历角色列表(,将每个角色显示到屏幕上);
# 然后再循环后面添加一个不缩进的代码块 →→在屏幕上绘制所有角色后设置一个Play Now按钮。
4.2 避免缩进错误
In [12]:
# python根据缩进来判断代码行与前一个代码行的关系
In [13]:
# python 通过使用缩进让代码更易读。
最为常见的缩进错误
In [14]:
# ①忘记缩进:
# 如果忘记缩进,Python会提醒你:
magicians = ['laura', 'andrew', 'sarah']
for magician in magicians:
print(magician)
Cell In[14], line 5 print(magician) ^IndentationError: expected an indented block after 'for' statement on line 4
In [19]:
# ^:提示错误的地方
# 【tips】:通常紧跟在for语句后面的代码行缩进 。
In [20]:
# ②忘记缩进额外的代码行:
# 逻辑错误,eg:只循环了最后一行:
magicians = ['laura', 'andrew', 'sarah']
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")
Laura, that was a great trick!
Andrew, that was a great trick!
Sarah, that was a great trick!
I can't wait to see your next trick, Sarah.
In [21]:
# ③不必要的缩进:
message = "Hello Pyhthon"
print(message)
Cell In[21], line 3 print(message) ^IndentationError: unexpected indent
In [22]:
# 【tips】:在前面编写的程序中,只有要在for循环中对每个元素执行的代码需要缩进。
In [23]:
# ④循环后不必要的缩进:
# magicians = ['laura', 'andrew', 'sarah']
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.") # 不小心缩进了此行,注意以下展示。
Laura, that was a great trick!
I can't wait to see your next trick, Laura.
Thank you,everyone.
Andrew, that was a great trick!
I can't wait to see your next trick, Andrew.
Thank you,everyone.
Sarah, that was a great trick!
I can't wait to see your next trick, Sarah.
Thank you,everyone.
In [24]:
# ⑤遗漏了for语句默默为的冒号:
# magicians = ['laura', 'andrew', 'sarah']
for magician in magicians
print(magician)
Cell In[24], line 3 for magician in magicians ^SyntaxError: expected ':'
4.3 创建数值列表
In [25]:
# 使用函数range() :打印一系列数
In [26]:
for value in range (1,5):
print(value)
# 在这个实例中,染个()只打印数1-4。输出数值不包含5.
1
2
3
4
In [27]:
# 如果要打印数1-5,需要使用range(1,6):
for value in range (1,6):
print(value)
1
2
3
4
5
In [28]:
# 调用函数range()时,也可指指定一个参数,这样它将从0开始。
# eg.range(6)返回数值0-6.
使用range()创建数字列表。
In [29]:
# 使用函数list()将range()的结果直接转换为列表。
# 如果将range()作为list()的参数,输出将是一个数字列表。
numbers = list(range(1,6))
print(numbers)
[1, 2, 3, 4, 5]
In [30]:
# 函数range()还可以指定步长。
# 给这个函数指定第三个参数,生成步长数。
even_numbers = list(range(2,11,2))
print(even_numbers)
[2, 4, 6, 8, 10]
In [31]:
# 创建一个列表,其中包含前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]
In [32]:
#【eg】:print(square)
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(square)
100
In [33]:
# squares.append(square):将新计算得到的平方值附加到列表squares末尾
# print(squares):打印列表squares
In [34]:
# 不使用临时变量square:
squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [35]:
# 首先应该考虑的是,编写清晰易懂且能完成所需的代码,
# 等到审核代码时候,再考虑采用更高效的方法
对数字列表执行简单的统计计算
In [36]:
# 最大,最小,总和
In [37]:
digits = range(1,20)
max(digits)
min(digits)
sum(digits)
Out[37]:
190
In [38]:
digits = [1,2,3,4,5,6,7,8,9,0]
max(digits)
min(digits)
sum(digits)
Out[38]:
45
In [39]:
digits = [1,2,3,4,5,6,7,8,9,0]
max(digits)
Out[39]:
9
In [40]:
min(digits)
Out[40]:
0
In [41]:
sum(digits)
Out[41]:
45
In [42]:
digits = [range(1,20)]
max(digits)
min(digits)
sum(digits)
---------------------------------------------------------------------------TypeError Traceback (most recent call last)
Cell In[42], line 4 2 max(digits) 3 min(digits)----> 4 sum(digits)
TypeError: unsupported operand type(s) for +: 'int' and 'range'
列表解析
In [43]:
# 前面介绍的生成squares的方式包含三四行代码,而列表解析让你只需编写一行代码就能生成这样的列表。
# 当编写三四行代码来生成列表有点频繁时,就可以考虑创建列表解析。
squares = [value**2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [44]:
# 请注意,这个for语句末尾没有冒号。
In [45]:
# 如果输出的时间太长,按 Ctrl+C 即可停止输出或关闭输出窗口。
In [46]:
# 立方:将同一个数乘三次成为立方。 eg.2的立方:2**3
4.4 切片(即:使用列表的一部分)
In [47]:
# 创建切片,可指定要使用的第一个元素和最后一个元素的索引。
In [48]:
# 要输出列表中的前三个元素,需要指定索引0和3,这将返回索引为0、1、2的元素。
players = ['laura', 'andrew', 'sarah', 'bob', 'david']
print(players[0:3])
['laura', 'andrew', 'sarah']
In [49]:
# 提取列表的第2、3、4个元素:
players = ['laura', 'andrew', 'sarah', 'bob', 'david']
print(players[1:4])
['andrew', 'sarah', 'bob']
In [50]:
# 如果没有指定第一个索引,python将自动从列表开头开始:
players = ['laura', 'andrew', 'sarah', 'bob', 'david']
print(players[:4])
['laura', 'andrew', 'sarah', 'bob']
In [51]:
# 要让切片终止于列表末尾:
players = ['laura', 'andrew', 'sarah', 'bob', 'david']
print(players[2:])
['sarah', 'bob', 'david']
In [52]:
# 输出名单上的最后三名队友,可使用切片players[-3:] :
players = ['laura', 'andrew', 'sarah', 'bob', 'david']
print(players[-3:])
['sarah', 'bob', 'david']
In [53]:
# 可在表示切片的方括号内指定第三个值,这个值告诉python在指定范围内每间隔多少元素提取一个。
遍历切片
In [54]:
players = ['laura', 'andrew', 'sarah', 'bob', 'david']
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:
Laura
Andrew
Sarah
In [55]:
# 切片很有用:eg.
# 编写游戏时,可以在玩家退出游戏时将其最终得分加入一个列表中,然后将该列表按降序排列以获取三个最高得分,再创建一个只包含前三个得分的切片;
# 处理数据时,可使用切片来进行批量处理;
# 编写Web应用程序时,可使用切片来分页显示所有信息,并在每页显示数量合适的信息。
复制列表: 方法( [:],即整个列表的副本。)
In [56]:
my_foods = ['pizza', 'falafel','cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:") #\n:要在里面
print(friend_foods)
My favorite foods are:
['pizza', 'falafel', 'cake']
My friend's favorite foods are:
['pizza', 'falafel', 'cake']
In [57]:
my_foods = ['pizza', 'falafel','cake']
friend_foods = my_foods[:]
my_foods.append('fried')
friend_foods.append('cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:") #\n:要在里面
print(friend_foods)
My favorite foods are:
['pizza', 'falafel', 'cake', 'fried']
My friend's favorite foods are:
['pizza', 'falafel', 'cake', 'cream']
In [58]:
# 如果将my_foods赋值给friend_foods,则不能得到两个不同的列表。
my_foods = ['pizza', 'falafel','cake']
friend_foods = my_foods # 对比 friend_foods = my_foods[:]
my_foods.append('fried')
friend_foods.append('cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:") #\n:要在里面
print(friend_foods)
# 即不饿能得到我们想要的结果。
My favorite foods are:
['pizza', 'falafel', 'cake', 'fried', 'cream']
My friend's favorite foods are:
['pizza', 'falafel', 'cake', 'fried', 'cream']
4.5 元组
In [59]:
# 列表非常适合用于存储在程序运行期间 可能变化 的数据集。
# 列表时可修改的。 eg.处理网站的用户列表,或游戏中的角色列表。
# 有时候你需要创建一系列不可修改的元素。
# Python将不能修改的值称为不可变的, 元组:不可变的列表。
In [60]:
# 元组看起来很像列表,但使用圆括号而非中括号来标识。
# 可使用索引来访问元组的元素。
# eg.如果有一个大小不应改变的矩形,可将其长度和宽度存储在一个元组中,从而确保他们是不能修改的:
dimensions = (10,5)
print(dimensions[0])
print(dimensions[1])
10
5
In [61]:
# 尝试修改元组dimensions的一个元素,观察结果:
dimensions = (10,5)
dimensions[0] = 25
---------------------------------------------------------------------------TypeError Traceback (most recent call last)
Cell In[61], line 3 1 # 尝试修改元组dimensions的一个元素,观察结果: 2 dimensions = (10,5)----> 3 dimensions[0] = 25
TypeError: 'tuple' object does not support item assignment
In [62]:
# 将会导致python返回类型错误消息。
In [63]:
# 如果你要定义只包含一个元素的元组,必须在这个元素后面加上逗号: eg. my_t = (3,)
遍历元组中的所有值
In [64]:
# 像列表一样,也可以使用for循环来遍历元组中的所有值:
dimensions = (10,5)
for dimension in dimensions:
print(dimension)
10
5
修改元组变量
In [65]:
# 虽然不能修改元组的元素,但可以给存储元组的变量赋值:即重新定义整个元组。
dimensions = (10,5)
print("original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (20,15)
print("\nmodified dimensions:")
for dimension in dimensions:
print(dimension)
original dimensions:
10
5
modified dimensions:
20
15
4.6 设置代码格式(格式设置指南)
In [66]:
# 目的:易于阅读;成为专业程序员
In [67]:
# Python改进提案(Python Enhancement Proposal),即PEP(eg.PEP8)
# 请访问Python网站,搜索“PEP8-Style Guide for Python Code”
# 原因:代码被阅读的次数比编写的次数多:
# 需要阅读:eg.代码编写写出来调试时;给程序添加新功能时;与其他程序员分享代码时。
# ①缩进:使用制表符,而不用空格。
# ②行长:建议注释的行长不应超过72字符。
# ③空行:要将程序的不同部分分开时,可使用空行,但不能滥用,不应使用三四个空行隔开。