当前位置: 首页 > news >正文

Python编程基础(三) | 操作列表

引言:很久没有写 Python 了,有一点生疏。这是学习《Python 编程:从入门到实践(第3版)》的课后练习记录,主要目的是快速回顾基础知识。

练习1:比萨

想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用for循环将每种比萨的名称打印出来。

  • 修改这个for循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对于每种比萨都显示一行输出,如下所示。

I like pepperoni pizza.

  • 在程序末尾添加一行代码(不包含在for循环中),指出你有多喜欢比萨。输出应包含针对每种比萨的消息,还有一个总结性的句子,如下所示。

I really love pizza!

pizzas = ["cheese", "pepperoni", "pineapple"]
for pizza in pizzas:print(f"I like {pizza} pizza.")
print("I really love pizza!")
I like cheese pizza.
I like pepperoni pizza.
I like pineapple pizza.
I really love pizza!

知识点回顾:

  • 列表(List)创建:使用方括号 [] 定义列表,元素之间用逗号 , 分隔。
  • for 循环:遍历列表中的每个元素。语法为 for item in list_name:
  • f-string (格式化字符串字面量):在字符串前加上 f,并用花括号 {} 嵌入变量或表达式,方便构建动态字符串。
  • print() 函数:用于将文本或变量的值输出到控制台。

练习2:动物

想出至少三种有共同特征的动物,将其名称存储在一个列表中,再使用for循环将每种动物的名称打印出来。

  • 修改这个程序,使其针对每种动物都打印一个句子,如下所示。

A dog would make a great pet.

  • 在程序末尾添加一行代码,指出这些动物的共同之处,如打印下面这样的句子。

Any of these animals would make a great pet!

animals = ["cat", "dog", "parrot"]
for animal in animals:print(f"A {animal} would make a great pet.")
print("Any of these animals would make a great pet!")
A cat would make a great pet.
A dog would make a great pet.
A parrot would make a great pet.
Any of these animals would make a great pet!

知识点回顾:

  • 列表应用:与练习1类似,再次练习列表的创建和遍历。
  • f-string 应用:通过 f-string 将列表中的动物名称嵌入到具有特定结构的句子中。
  • 循环后的总结性输出:在 for 循环外部使用 print() 函数输出总结性语句。

练习3:数到20

使用一个for循环打印数1~20(含)。

for number in range(1, 21):print(number)
1
2
3
... (输出将继续直到20)
19
20

知识点回顾:

  • range() 函数:用于生成一个数字序列。range(start, stop) 会生成从 start 开始到 stop-1 结束的整数序列。因此,range(1, 21) 会生成 1 到 20 的数字。
  • for 循环与 range() 结合:常用于执行固定次数的迭代或遍历数字序列。

练习4: 100万

创建一个包含数1~1 000 000的列表,再使用一个for循环将这些数打印出来。(如果输出的时间太长,按Ctrl + C停止输出,或关闭输出窗口。)

numbers = list(range(1, 1000001))
# 为了避免实际打印大量数据导致过长等待,以下循环通常会注释掉或只打印部分
# for number in numbers:
#     print(number)
print("List created with 1,000,000 numbers. Printing is typically skipped for brevity.")
print(f"First few numbers: {numbers[:5]}")
print(f"Last few numbers: {numbers[-5:]}")
List created with 1,000,000 numbers. Printing is typically skipped for brevity.
First few numbers: [1, 2, 3, 4, 5]
Last few numbers: [999996, 999997, 999998, 999999, 1000000]

(注意:实际按题目要求运行 for number in numbers: print(number) 会输出1到100万所有数字,这里仅为演示列表创建)

知识点回顾:

  • list(range()):将 range() 函数生成的序列直接转换为列表。
  • 处理大数据量:创建包含大量元素的列表是可行的,但遍历并打印每个元素可能会非常耗时。
  • 中断执行:提示用户可以使用 Ctrl + C 来中断长时间运行的程序。

练习5: 100万求和

创建一个包含数1~1 000 000的列表,再使用min()max()核实该列表确实是从1开始、到1 000 000结束的。另外,对这个列表调用函数sum(),看看Python将100万个数相加需要多长时间。

import time # 导入time模块来粗略计算时间numbers = list(range(1, 1000001))print(f"Min value: {min(numbers)}")
print(f"Max value: {max(numbers)}")start_time = time.time()
total_sum = sum(numbers)
end_time = time.time()print(f"Sum: {total_sum}")
print(f"Time taken to sum: {end_time - start_time:.6f} seconds")
Min value: 1
Max value: 1000000
Sum: 500000500000
Time taken to sum: 0.026786 seconds (时间会因机器性能而异)

知识点回顾:

  • min(list) 函数:返回列表中的最小值。
  • max(list) 函数:返回列表中的最大值。
  • sum(list) 函数:返回列表中所有数值型元素的和。
  • 性能考量:Python 内置函数(如 sum())通常经过优化,执行效率较高。
  • time 模块 (可选):可用于简单地测量代码段的执行时间。

练习6:奇数

通过给range()函数指定第三个参数来创建一个列表,其中包含1~20的奇数;再使用一个for循环将这些数打印出来。

odd_numbers = list(range(1, 21, 2))
for num in odd_numbers:print(num)
1
3
5
7
9
11
13
15
17
19

知识点回顾:

  • range(start, stop, step) 函数:第三个参数 step 指定了序列中数字之间的步长(间隔)。range(1, 21, 2) 表示从1开始,不超过20,步长为2,从而生成奇数序列。

练习7: 3的倍数

创建一个列表,其中包含3~30内能被3整除的数,再使用一个for循环将这个列表中的数打印出来。

multiples_of_three = list(range(3, 31, 3))
for number in multiples_of_three:print(number)
3
6
9
12
15
18
21
24
27
30

知识点回顾:

  • range() 与步长应用:通过设置合适的起始值、结束值和步长,可以方便地生成特定规律的数字序列,如倍数序列。

练习8:立方

将同一个数乘三次称为立方。例如,在Python中,2的立方用2**3表示。创建一个列表,其中包含前10个整数(1~10)的立方,再使用一个for循环将这些立方数打印出来。

cubes = []
for i in range(1, 11):cubes.append(i**3)for number in cubes:print(number)
1
8
27
64
125
216
343
512
729
1000

知识点回顾:

  • 幂运算符 **:用于计算乘方,x**y 表示 x 的 y 次方。
  • 列表 append() 方法:用于在列表末尾添加新元素。
  • 构建列表:通过循环计算每个值,并将其逐个添加到空列表中,是一种常见的列表构建方式。

练习9:立方推导式

使用列表推导式生成一个列表,其中包含前10个整数的立方。

cubes = [number**3 for number in range(1, 11)]
for number in cubes: # 或者直接 print(cubes)print(number)
1
8
27
64
125
216
343
512
729
1000

知识点回顾:

  • 列表推导式 (List Comprehension):一种简洁的创建列表的语法。基本形式为 [expression for item in iterable]。它将 for 循环和元素创建合并在一行代码中,使代码更易读、更紧凑。

练习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:”,再使用切片来打印列表末尾的三个元素。
# 沿用练习9的cubes列表
cubes = [number**3 for number in range(1, 11)]
print(f"The original list is: {cubes}")print("\nThe first three items in the list are:")
print(cubes[:3])# 为了选择中间的三个元素,我们需要确定列表长度和起始索引
# 列表长度为10,中间的三个可以是索引3, 4, 5或4, 5, 6等。
# 这里选择索引为列表长度整除2减1开始的三个,即第4、5、6个元素(索引3,4,5)
middle_start_index = len(cubes) // 2 - 1 # 对于长度10,这是 10//2 - 1 = 4
# 如果想更居中,对于偶数长度,可能需要更明确定义“中间”
# 这里简单选择从索引3开始的三个元素 (64, 125, 216)
print("\nThree items from the middle of the list are:")
print(cubes[3:6]) # 元素索引为3, 4, 5print("\nThe last three items in the list are:")
print(cubes[-3:])
The original list is: [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]The first three items in the list are:
[1, 8, 27]Three items from the middle of the list are:
[64, 125, 216]The last three items in the list are:
[512, 729, 1000]

知识点回顾:

  • 列表切片 (Slicing):允许访问列表的子集。
    • list_name[start:end]:从索引 start 开始到 end-1 的元素。
    • list_name[:end]:从列表开头到 end-1 的元素。
    • list_name[start:]:从索引 start 到列表末尾的元素。
    • list_name[-n:]:列表末尾的 n 个元素。
  • len() 函数:返回列表中的元素数量,可用于动态计算切片索引。

练习11:你的比萨,我的比萨

在你为练习1编写的程序中,创建比萨列表的副本,并将其赋给变量friend_pizzas,再完成如下任务。

  • 在原来的比萨列表中添加一种比萨。
  • 在列表friend_pizzas中添加另一种比萨。
  • 核实有两个不同的列表。为此,打印消息“My favorite pizzas are:”,再使用一个for循环来打印第一个列表;打印消息“My friend’s favorite pizzas are:”,再使用一个for循环来打印第二个列表。
pizzas = ["cheese", "pepperoni", "pineapple"]
friend_pizzas = pizzas[:] # 创建副本pizzas.append("meat lover's")
friend_pizzas.append("mushroom")print("My favorite pizzas are:")
for pizza in pizzas:print(f"- {pizza}")print("\nMy friend's favorite pizzas are:")
for pizza in friend_pizzas:print(f"- {pizza}")
My favorite pizzas are:
- cheese
- pepperoni
- pineapple
- meat lover'sMy friend's favorite pizzas are:
- cheese
- pepperoni
- pineapple
- mushroom

知识点回顾:

  • 复制列表:使用切片 [:] (如 friend_pizzas = pizzas[:]) 可以创建一个列表的浅副本。这意味着对一个列表的修改(如 append())不会影响另一个列表。
  • 列表 append() 方法:再次练习向列表末尾添加元素。
  • 独立性验证:通过分别修改和打印两个列表,可以验证它们是独立的副本。

练习12:使用多个循环

在本节中,为节省篇幅,程序foods.py的每个版本都没有使用for循环来打印列表。请选择一个版本的foods.py,在其中编写两个for循环,将各个食品列表都打印出来。

my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:] # 创建副本# 假设我们对列表进行一些修改以展示它们是独立的
my_foods.append('cannoli')
friend_foods.append('ice cream')print("My favorite foods are:")
for food in my_foods:print(f"- {food}")print("\nMy friend's favorite foods are:")
for food in friend_foods:print(f"- {food}")
My favorite foods are:
- pizza
- falafel
- carrot cake
- cannoliMy friend's favorite foods are:
- pizza
- falafel
- carrot cake
- ice cream

知识点回顾:

  • 重复练习:此练习主要是对列表复制、append() 方法以及使用 for 循环打印列表内容的巩固。
  • 代码组织:使用多个 for 循环分别处理和显示不同的数据集。
  • 换行符 \n:在 print 语句中使用 \n 可以在输出中插入一个空行,使输出更易读。

练习13:自助餐

有一家自助式餐馆,只提供5种简单的食品。请想出5种简单的食品,并将其存储在一个元组中。

  • 使用一个for循环将该餐馆提供的5种食品都打印出来。
  • 尝试修改其中的一个元素,核实Python确实会拒绝你这样做。
  • 餐馆调整菜单,替换了两种食品。请编写一行给元组变量赋值的代码,并使用一个for循环将新元组的每个元素都打印出来。
# 初始菜单
foods = ("牛肉", "鸡肉", "鱼肉", "蔬菜", "水果")
print("Original menu items:")
for food in foods:print(f"- {food}")# 尝试修改元组中的元素 (这将引发TypeError)
print("\nAttempting to change an item in the tuple...")
try:foods[0] = "羊肉"
except TypeError as e:print(f"Error: {e}")# 餐馆调整菜单,创建一个新的元组
print("\nRestaurant is updating the menu.")
new_foods = ("牛肉", "鸡肉", "兔肉", "沙拉", "汤类") # 替换了鱼肉、蔬菜、水果
print("New menu items:")
for new_food in new_foods:print(f"- {new_food}")
Original menu items:
- 牛肉
- 鸡肉
- 鱼肉
- 蔬菜
- 水果Attempting to change an item in the tuple...
Error: 'tuple' object does not support item assignmentRestaurant is updating the menu.
New menu items:
- 牛肉
- 鸡肉
- 兔肉
- 沙拉
- 汤类

知识点回顾:

  • 元组 (Tuple) 创建:使用圆括号 () 定义元组,元素之间用逗号 , 分隔。
  • 元组的不可变性 (Immutability):元组一旦创建,其元素就不能被修改、添加或删除。尝试修改元组元素会导致 TypeError
  • 遍历元组:与列表类似,可以使用 for 循环遍历元组中的每个元素。
  • 重新赋值元组变量:虽然不能修改元组本身,但可以给元组变量赋一个全新的元组,如 new_foods = (...)。这并没有改变原始的 foods 元组(如果它还在其他地方被引用的话),而是让 new_foods 指向了一个新的元组对象。
  • try-except 块 (可选):用于捕获和处理预期的错误,如本例中的 TypeError,使程序能优雅地处理错误而不是直接崩溃。

相关文章:

  • ESP32与STM32
  • 【MIMO稳定裕度】基于数据驱动的多输入多输出系统稳定裕度分析
  • ps曝光度调整
  • 408考研逐题详解:2009年第27题
  • 【笔记】Windows 下载并安装 ChromeDriver
  • SpringBoot(六)--- AOP、ThreadLocal
  • Hadoop学习笔记
  • 【算法设计与分析】实验——改写二分搜索算法,众数问题(算法分析:主要算法思路),有重复元素的排列问题,整数因子分解问题(算法实现:过程,分析,小结)
  • Java递归编程中的StackOverflowError问题分析与解决方案
  • 从“敲窗“到“推门“:用Requests库解锁网络数据的“读心术“——Python爬虫入门实战指南
  • SCAU8640--希尔排序
  • 通俗理解“高内聚,低耦合”
  • ipfs下载和安装(windows)
  • 50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | Sound Board(音响控制面板)
  • 回文字符串
  • 【烧脑算法】不定长滑动窗口:从动态调整到精准匹配以灵活特性实现高效破题
  • 小目标检测:YOLOV7改进之双坐标注意力(DCA)
  • YOLOv10改进|爆改模型|涨点|C2F引入空间和通道注意力模块暴力涨点(附代码+修改教程)
  • 【C盘瘦身】给DevEco Studio中HarmonyOSEmulator(鸿蒙模拟器)换个地方,一键移动给C盘瘦身
  • FreeRTOS实时操作系统学习笔记
  • 网站建设方案模板下载/公司网站设计的内容有哪些
  • 个人网站平台搭建/竞价推广哪家公司好
  • 网站域名销售/2345网址导航用户中心
  • apache多个网站/seo长尾关键词排名
  • 物流网站的建设/网络策划是做什么的
  • 福州公司网站设计/百度入口提交