1. 推导式是什么? #

类型 语法 结果
列表 [expr for x in iterable if 条件] list
字典 {k: v for x in iterable if 条件} dict
集合 {expr for x in iterable if 条件} set
生成器 (expr for x in iterable if 条件) generator

2. 列表推导式 #

# 基本映射:生成 0~4 的平方
squares = [x ** 2 for x in range(5)]
print(squares)
# 带 if 过滤:保留偶数
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
# 表达式里三元运算
labels = ["even" if x % 2 == 0 else "odd" for x in range(3)]
print(labels)
# 用户列表
users = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
# 提取所有用户名
names = [u["name"] for u in users]
# 提取 active 用户的 id
active_ids = [u["id"] for u in users if u.get("active")]
# 二维列表
matrix = [[1, 2], [3, 4]]
# 展平为一维列表
flat = [n for row in matrix for n in row]
# 用普通循环展平二维列表
flat = []
for row in matrix:
    for n in row:
        flat.append(n)

3. 字典推导式 #

# 基本:生成数字到平方的映射
squares = {x: x ** 2 for x in range(5)}

# 过滤原字典:只保留及格分
scores = {"Alice": 85, "Bob": 58, "Charlie": 71}
passed = {name: score for name, score in scores.items() if score >= 60}
# 不及格分数改为 None
result = {
    name: score if score >= 60 else None
    for name, score in scores.items()
}

4. 集合推导式 #

# 标签列表(含重复)
tags = ["py", "web", "py", "api"]
# 生成唯一标签集合
unique = {t for t in tags}

5. 生成器表达式 #

# 定义带打印副作用的函数
def double(x):
    print(f"Doubling {x}...")
    return x * 2

# 生成器表达式:惰性求值,不会立即执行
evens = (double(x) for x in range(10) if x % 2 == 0)
print(evens)

# 消费生成器,转为列表时才真正执行
print(list(evens))

6. 何时用、何时不用 #

# 从用户列表生成 API URL
urls = [f"/api/users/{u['id']}" for u in users]

7. 项目开发要点 #

8. 总结 #

类型 典型场景
列表 [...] 映射、过滤、提取字段
字典 {...} 过滤/改造字典
集合 {...} 去重、唯一值
生成器 (...) 大数据、传给 sum/any 等