第4章 操作列表
本章目标:掌握 for 循环遍历列表、range() 生成数值、切片操作、元组使用以及代码格式规范。
4.1 遍历整个列表
使用 for 循环遍历列表:
python
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
输出:
alice
david
carolina
过程说明:
- Python 从列表中取出第一个值
'alice',存入变量magician - 执行缩进的代码块(打印
magician) - 返回循环首行,取下一个值
'david',重复执行 - 直到列表元素用完,循环结束
4.1.1 深入地研究循环
-
对列表中的每个元素,循环都执行指定的步骤
-
不管列表有多少元素,Python 都会逐一处理
-
临时变量名应具有描述性:
pythonfor cat in cats: # 小猫列表 for dog in dogs: # 小狗列表 for item in list_of_items: # 通用列表
4.1.2 在 for 循环中执行更多的操作
python
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.`
`
`
关键 :在
for循环中,每个缩进的代码行都会对每个元素执行一次。
4.1.3 在 for 循环结束后执行一些操作
python
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!")`
`
`
不缩进的代码只执行一次,在循环结束后执行。
4.2 避免缩进错误
4.2.1 忘记缩进
python
for magician in magicians:
print(magician) # ❌ 没有缩进
→ IndentationError: expected an indented block
4.2.2 忘记缩进额外的代码行
python
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 只在循环结束后执行一次(仅输出最后一次的值)。Python 不会报错,但结果不符合预期。
4.2.3 不必要的缩进
python
message = "Hello Python world!"
print(message) # ❌ 不该缩进却缩进了
→ IndentationError: unexpected indent
4.2.4 循环后不必要的缩进
python
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("Thank you everyone, that was a great magic show!") # ❌ 这条应在循环外
→ 逻辑错误:感谢消息被重复打印了三次。
4.2.5 遗漏了冒号
python
for magician in magicians # ❌ 缺少冒号
print(magician)
→ SyntaxError
4.3 创建数值列表
4.3.1 range() 函数
python
for value in range(1, 5):
print(value)
# 输出:1 2 3 4(不含5)
for value in range(1, 6):
print(value)
# 输出:1 2 3 4 5
range(start, stop)从 start 开始,到 stop-1 结束。
4.3.2 使用 range() 创建数字列表
python
# range() 转列表
numbers = list(range(1, 6))
print(numbers) # [1, 2, 3, 4, 5]
# 指定步长(偶数)
even_numbers = list(range(2, 11, 2))
print(even_numbers) # [2, 4, 6, 8, 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]
# 更简洁的写法(不使用临时变量)
`squares = []`
`
for value in range(1, 11):`
`
squares.append(value ** 2)`
`
`
4.3.3 对数字列表执行统计计算
python
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
4.3.4 列表解析
一行代码生成列表:
python
squares = [value**2 for value in range(1, 11)]
print(squares)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
语法结构:
[表达式 for 变量 in 可迭代对象]
for语句末尾没有冒号- 表达式和 for 循环合并成一行
4.4 使用列表的一部分(切片)
4.4.1 切片
python
players = ['charles', 'martina', 'michael', 'florence', 'eli']
`print(players[0:3]) # 索引 0~2 → ['charles', 'martina', 'michael']`
`
print(players[1:4]) # 索引 1~3 → ['martina', 'michael', 'florence']`
`
print(players[:4]) # 开头到索引 3 → ['charles', 'martina', 'michael', 'florence']`
`
print(players[2:]) # 索引 2 到末尾 → ['michael', 'florence', 'eli']`
`
print(players[-3:]) # 最后三个 → ['michael', 'florence', 'eli']`
`
`
4.4.2 遍历切片
python
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
4.4.3 复制列表
正确方式 --- 使用切片 [:]:
python
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:] # 复制整个列表
my_foods.append('cannoli')
friend_foods.append('ice cream')
`print(my_foods) # ['pizza', 'falafel', 'carrot cake', 'cannoli']`
`
print(friend_foods) # ['pizza', 'falafel', 'carrot cake', 'ice cream']`
`
`
错误方式 --- 直接赋值(两个变量指向同一个列表):
python
friend_foods = my_foods # ❌ 不是复制,两个变量指向同一个列表
my_foods.append('cannoli')
friend_foods.append('ice cream')
# 两个列表都包含 'cannoli' 和 'ice cream'
4.5 元组
元组 :不可变的列表,用圆括号 () 表示。
4.5.1 定义元组
python
dimensions = (200, 50)
print(dimensions[0]) # 200
print(dimensions[1]) # 50
# ❌ 尝试修改元组元素会报错
`dimensions[0] = 250 # TypeError: 'tuple' object does not support item assignment`
`
`
4.5.2 遍历元组
python
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
4.5.3 修改元组变量
不能修改元组的元素,但可以重新赋值整个元组变量:
python
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
`dimensions = (400, 100) # 重新赋值`
`
print("\nModified dimensions:")`
`
for dimension in dimensions:`
`
print(dimension)`
`
`
4.6 设置代码格式(PEP 8)
| 规范 | 说明 |
|---|---|
| 缩进 | 每级缩进使用 4 个空格,不要混用制表符和空格 |
| 行长 | 每行不超过 79 字符 ,注释不超过 72 字符 |
| 空行 | 用空行分隔代码的不同部分,但不要滥用 |
| PEP 8 | 完整的 Python 代码格式指南:https://python.org/dev/peps/pep-0008/ |
动手试一试
4-1 比萨
python
pizzas = ['pepperoni', 'margherita', 'hawaiian']
for pizza in pizzas:
print("I like " + pizza + " pizza")
print("I really love pizza!")
4-2 动物
python
animals = ['dog', 'cat', 'rabbit']
for animal in animals:
print("A " + animal + " would make a great pet")
print("Any of these animals would make a great pet!")
4-3 数到 20
python
for value in range(1, 21):
print(value)
4-4 ~ 4-5 一百万
python
numbers = list(range(1, 1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
4-6 奇数
python
odd_numbers = list(range(1, 21, 2))
for number in odd_numbers:
print(number)
4-7 3 的倍数
python
multiples = list(range(3, 31, 3))
for number in multiples:
print(number)
4-8 ~ 4-9 立方
python
# 普通写法
cubes = []
for value in range(1, 11):
cubes.append(value ** 3)
print(cubes)
# 列表解析写法
`cubes = [value ** 3 for value in range(1, 11)]`
`
print(cubes)`
`
`
4-10 切片
python
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("The first three items in the list are:")
print(players[:3])
print("Three items from the middle of the list are:")
print(players[1:4])
`print("The last three items in the list are:")`
`
print(players[-3:])`
`
`
4-11 你的比萨和我的比萨
python
my_pizzas = ['pepperoni', 'margherita', 'hawaiian']
friend_pizzas = my_pizzas[:]
my_pizzas.append('sicilian')
friend_pizzas.append('neapolitan')
print("My favorite pizzas are:")
for pizza in my_pizzas:
print(pizza)
`print("\nMy friend's favorite pizzas are:")`
`
for pizza in friend_pizzas:`
`
print(pizza)`
`
`
4-13 自助餐
python
foods = ('rice', 'noodles', 'soup', 'salad', 'bread')
for food in foods:
print(food)
# foods[0] = 'pizza' # ❌ 会报错
`foods = ('pizza', 'noodles', 'soup', 'salad', 'cake')`
`
for food in foods:`
`
print(food)`
`
`
代码块汇总
python
# for 循环
for magician in magicians:
print(magician)
# range()
for value in range(1, 5): # 1~4
list(range(1, 11, 2)) # [1, 3, 5, 7, 9]
# 统计
min(digits)
max(digits)
sum(digits)
# 列表解析
squares = [value**2 for value in range(1, 11)]
# 切片
players[0:3] # 前三个
players[:4] # 开头到索引3
players[2:] # 索引2到末尾
players[-3:] # 最后三个
players[:] # 复制整个列表
# 元组
`dimensions = (200, 50) # 用圆括号`
`
dimensions[0] = 250 # ❌ 不允许修改`
`
dimensions = (400, 100) # ✅ 可以重新赋值`
`
`
常见错误 / 陷阱
| 错误类型 | 说明 | 解决 |
|---|---|---|
IndentationError |
缩进错误(忘记缩进或多余缩进) | 检查缩进级别 |
| 逻辑错误 | 循环内的代码只执行了一次,或循环外的代码重复执行 | 检查缩进是否正确 |
SyntaxError |
for 语句末尾缺冒号 | 在 for 行末尾加 : |
TypeError |
尝试修改元组元素 | 元组不可变,需重新赋值 |
| 列表复制失败 | 直接赋值导致两个变量指向同一列表 | 用 [:] 切片复制 |
复习要点
-
for 变量 in 列表:遍历列表,缩进的代码块是循环体 -
range(start, stop, step)生成数值序列(不含 stop) -
list(range(...))将 range 转为列表 -
min()/max()/sum()数字列表统计 - 列表解析
[表达式 for 变量 in 可迭代对象] - 切片
list[start:end],省略 start 从头开始,省略 end 到末尾 -
list[:]复制列表,不要用直接赋值 - 元组 用
(),元素不可修改,变量可重新赋值 - PEP 8:4 空格缩进、79 字符行长、合理空行
学习时的困惑
🤔 for 循环缩进:一开始老搞不清哪些代码在循环里
第一次写 for magician in magicians: 的时候,后面写的代码忘记缩进,结果循环只执行了一次。记住一个规则:缩进的就是循环体,没缩进的就是循环外面。
🤔 range() 的 stop 参数永远取不到
range(1, 5) 返回 1、2、3、4,没有 5。第一次用的时候老写错,后来记了个口诀:"写的时候想最后一个数,就写那个数+1" 。想要 1-10 就写 range(1, 11)。
🤔 列表解析:第一次看到差点劝退
python
squares = [value**2 for value in range(1, 11)]
第一次看到这行代码,我看了半分钟才看懂它在干什么。但是一旦习惯了,写起来是真快------比写 4 行 for 循环爽多了。
🤔 元组 vs 列表:学完一章还没搞清楚区别
当时觉得"那为啥还要用元组?"后来在实际项目中懂了------元组用来存不该被改的数据,比如一年的月份、一周的天数。Python 会在你试图修改时报错,这就是保障。
跟我工作的关系
| 知识点 | 能用在哪 |
|---|---|
for 循环遍历 |
遍历 WorkBuddy 的自动化任务列表,逐个执行 |
range() 生成序列 |
生成文章编号、任务序号,比如 for i in range(1, 11) |
| 列表解析 | 一行代码从笔记列表过滤出含某个关键词的文件名 |
list[:] 复制列表 |
在自动化脚本里处理数据前先复制一份,保护原始数据 |
| 元组 | 存储固定的配置项,比如一周七天的自动化时间表 |
实战小项目(TODO)
写一个脚本,用 for 循环遍历 Obsidian 中所有 .md 文件名,用列表解析过滤出含 "Python" 的笔记,输出文件数量统计。