书籍说明
书名:《Python编程:从入门到实践》(第一版)/Python Crash Course: A Hands-On, Project-Based Introduction to Programming
作者:Eric Matthes(著)/袁国忠(译)
出版社:人民邮电出版社
开发环境说明
Python Version: 3.11.2
Python IDE: PyCharm Community Edition 2022.3.3
目录
第4章 操作列表
4.1 遍历整个列表
4.1.1 深入地研究循环
4.1.2 在for循环中执行更多的操作
4.1.3 在for循环结束后执行一些操作
4.2 避免缩进错误
4.2.1 忘记缩进
4.2.2 忘记缩进额外的代码行
4.2.3 不必要的缩进
4.2.4 循环后不必要的缩进
4.2.5 遗漏了冒号
动手试一试
4.3 创建数字列表
4.3.1 使用函数range( )
4.3.2 使用range( )创建数字列表
4.3.3 对数字列表执行简单的统计计算
4.3.4 列表解析
动手试一试
4.4 使用列表的一部分
4.4.1 切片
4.4.2 遍历切片
4.4.3 复制列表
动手试一试
4.5 元组
4.5.1 定义元祖
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")
输出结果:
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.
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!")
输出结果:
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-1 比萨:想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用for循环将每种比萨的名称都打印出来。
修改这个for循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对于每种比萨,都显示一行输出,如“I like pepperoni pizza”。
在程序末尾添加一行代码,它不在for循环中,指出你有多喜欢比萨。输出应包含针对每种比萨的消息,还有一个总结性句子,如“I really love pizza!”。
pizzas = ['Margherita', 'New York Style', 'Chicago Style'] for pizza in pizzas: print("I like " + pizza + "pizza.") print("I really love pizza!")
输出结果:
I like Margheritapizza.
I like New York Stylepizza.
I like Chicago Stylepizza.
I really love pizza!4-2 动物:想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for循环将每种动物的名称都打印出来。
修改这个程序,使其针对每种动物都打印一个句子,如“A dog would make a great pet”。
在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如“Any of these animals would make a great pet!”这样的句子。
pets = ['dog', 'cat', 'rabbit'] for pet in pets: print("A " + pet + " would make a great pet.") print("Any of these animals would make a great pet!")
输出结果:
A dog would make a great pet.
A cat would make a great pet.
A rabbit would make a great pet.
Any of these animals would make a great pet!
for value in range(1,5):
print(value)
输出结果:
1
2
3
4
numbers = list(range(1,6))
print(numbers)
输出结果:[1, 2, 3, 4, 5]
使用range( )函数时,还可以指定步长。例如,下面的代码打印1~10内的偶数:
even_numbers = list(range(2,11,2))
print(even_numbers)
输出结果:[2, 4, 6, 8, 10]
例如,创建一个包含前10个整数(即1~10)的平方的列表:
squares = [] #创建一个空列表squares
for value in range(1,11): #遍历1~10的值
square = value**2 #计算当前值的平方,并将结果存储到变量square中
squares.append(square) #将新计算得到的平方值附加到列表squares末尾
print(squares)
#下面是简洁的方法
squares = []
for value in range(1,11):
squares.qppend(value**2)
print(squares)
输出结果:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
输出结果:
0
9
45
squares = [value**2 for value in range(1,11)]
print(squares)
输出结果:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
动手试一试
4-3 数到20:使用一个for循环打印数字1~20(含)。
for value in range(1,21): print(value)
输出结果:(略)
4-4 一百万:创建一个列表,其中包括数字1~1000000,再使用一个for循环将这些数字打印出来(如果输出的时间太长,按Crt+C停止输出,或关闭输出窗口)。
numbers = list(range(1,1000001)) print(numbers)
输出结果:(略)
4-5 计算1~1000000的总和:创建一个列表,其中包含数字1~1000000,再使用min( )和max( )核实该列表确实是从1开始,到1000000结束的。另外,对这个列表调用函数sum( ),看看Python将一百万个数字相加需要多长时间。
numbers = list(range(1,1000001)) print(min(numbers)) print(max(numbers)) print(sum(numbers))
输出结果:
1
1000000
5000005000004-6 奇数:通过给函数range( )指定第三个参数来创建一个列表,其中包含1~20的奇数;再使用一个for循环将这些数字都打印出来。
numbers = list(range(1,20,2)) for number in numbers: print(number)
输出结果:
1
3
5
7
9
11
13
15
17
194-7 3的倍数:创建一个列表,其中包含3~30内能被3整除的数字;再使用一个for循环将这个列表中的数字都打印出来。
numbers =[] for value in range(1,11): numbers.append(value*3) print(numbers)
输出结果:[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
4-8 立方:请创建一个列表,其中包含前10个整数(即1~10)的立方,再使用一个for循环将这些立方数都打印出来。
numbers =[] for value in range(1,11): numbers.append(value**3) print(numbers)
输出结果:[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
4-9 立方解析:使用列表解析生成一个列表,其中包含前10个整数的立方。
cubes = [value**3 for value in range(1,11)] print(cubes)
输出结果:[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])
输出结果:
['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
players = ['charles', '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:
Charles
Martina
Michael
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']
动手试一试
4-10 切片:选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。
- 打印消息“The first three items in the list are:”,再使用切片来打印列表的前三个元素。
- 打印消息“Three items from the middle of the list are:”,再使用切片来打印列表中间的三个元素。
- 打印消息“The last three items in the list are:”,再使用切片来打印列表末尾的三个元素。
friends = ['Rachel', 'Monica', 'Phoebe', 'Joey', 'Chandler', 'Ross', 'Lucy'] print("The first three items in the list are:") for friend in friends[:3]: print(friend) print("\nThree items from the middle of the list are:") for friend in friends[2:5]: print(friend) print("\nThe last three items in the list are:") for friend in friends[-3:]: print(friend)
输出结果:
The first three items in the list are:
Rachel
Monica
Phoebe
Three items from the middle of the list are:
Phoebe
Joey
Chandler
The last three items in the list are:
Chandler
Ross
Lucy4-11 你的比萨和我的比萨:在你为完成练习4-1而编写的程序中,创建比萨列表的副本,并将其存储到变量friends_pizzas中,再完成如下任务。
- 在原来的比萨列表中添加一种比萨。
- 在列表friends_pizzas中添加另一种比萨。
- 核实你有两个不同的列表。为此,打印消息“My favorite pizzas are:”,再使用一个for循环来打印第一个列表;打印消息“My friend's favorite pizzas are:”,再使用一个for循环来打印第二个列表。核实新增的比萨被添加到了正确的列表中。
pizzas = ['Margherita', 'New York Style', 'Chicago Style'] friends_pizzas = pizzas[:] pizzas.append('good') friends_pizzas.append('better') print("My favorite pizzas are:") for pizza in pizzas: print(pizza) print("\nMy friend's favorite pizzas are:") for friends_pizza in friends_pizzas: print(friends_pizza)
输出结果:
My favorite pizzas are:
Margherita
New York Style
Chicago Style
good
My friend's favorite pizzas are:
Margherita
New York Style
Chicago Style
better4-12 使用多个循环:在本节中,为节省篇幅,程序foods.py的每个版本都没有使用for循环来打印列表。请选择一个版本的foods.py,在其中编写两个for循环,将各个食品列表都打印出来。
my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] print("My favorite foods are:") for my_food in my_foods: print(my_food) print("\nMy friend's favorite foods are:") for friend_food in friend_foods: print(friend_food)
输出结果:
My favorite foods are:
pizza
falafel
carrot cakeMy friend's favorite foods are:
pizza
falafel
carrot cake
(剩余4.6内容省略)