我靠列表推导式,把 10 行代码变成 1 行
✨ 同事说我是代码魔法师
列表推导式和 lambda 是 Python 代码优雅的标志。
90% 的新手在用循环写代码,老手一行推导式搞定。
你的代码会像诗一样优雅。
"小雪,我写了个函数处理数据,有 50 行代码。同事说太啰嗦,让我看看能不能优化,但我不知道从哪下手。"
我问她:"能看看代码吗?"
她发过来一看——全是基础循环,完全可以用推导式!
result = []
for item in data:
if item['price'] > 100:
result.append(item['name'].upper())
这不就是列表推导式的标准场景吗?
我给她改了代码:
result = [item['name'].upper() for item in data if item['price'] > 100]
✅ 50 行→5 行,同事看傻了。
昨天她给我发消息:"现在我的代码全是推导式,同事说我是代码魔法师,老板让我给团队做分享。"
这不是魔法,是掌握了正确的语法。✿
| 5 行 | ||
| 一眼看懂 | ||
| 1 分钟 | ||
| 低(语法简单) | ||
| "代码魔法师" | ||
| "可以带团队" |
算一笔账:每天省 10 分钟,一年省下60 小时,相当于多干 2.5 天活。
# 普通循环写法
result = []
for i in range(5):
result.append(i * 2)
# 推导式写法
result = [i * 2 for i in range(5)]
print(result) # 输出:[0, 2, 4, 6, 8]
📚 讲解:
• 语法格式:[表达式 for 变量 in 列表]
• 读作:"对于列表中的每个变量,计算表达式"
• 结果是一个新列表
• 记忆口诀:推导式 = 循环 + 计算,一行搞定
# 普通循环写法
result = []
for i in range(10):
if i % 2 == 0:
result.append(i)
# 推导式写法
result = [i for i in range(10) if i % 2 == 0]
print(result) # 输出:[0, 2, 4, 6, 8]
📚 讲解:
• 语法格式:[表达式 for 变量 in 列表 if 条件]
• if 放在最后,过滤不符合条件的
• 记忆口诀:条件放在最后,像英语一样自然
# 普通循环写法
result = []
for i in range(3):
for j in range(3):
result.append((i, j))
# 推导式写法
result = [(i, j) for i in range(3) for j in range(3)]
print(result) # 输出:[(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]
📚 讲解:
• 多个 for 连写,顺序和嵌套循环一致
• 适用场景:处理二维数据
# 普通循环写法
result = {}
for i in range(5):
result[i] = i ** 2
# 推导式写法
result = {i: i ** 2 for i in range(5)}
print(result) # 输出:{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
📚 讲解:
• 语法格式:{key: value for 变量 in 列表}
• 和列表推导式类似,只是用 {}
• 适用场景:快速生成字典
api_response = {
'data': [
{'id': 1, 'name': '小明', 'score': 85},
{'id': 2, 'name': '小红', 'score': 92},
{'id': 3, 'name': '小刚', 'score': 78},
]
}
# 普通循环写法
names = []
for item in api_response['data']:
if item['score'] >= 80:
names.append(item['name'])
# 推导式写法
names = [item['name'] for item in api_response['data'] if item['score'] >= 80]
print(names) # 输出:['小明', '小红']
📚 讲解:
• 处理 API 数据,推导式是标配
• 可以嵌套多层取值
• 重要:处理大模型 API 返回的多个结果时非常有用
lambda 是匿名函数,不用 def 定义名字:
# 普通函数写法
def add(x, y):
return x + y
# lambda 写法
add = lambda x, y: x + y
print(add(3, 5)) # 输出:8
📚 讲解:
• 语法格式:lambda 参数:表达式
• 自动返回表达式的结果
• 适用场景:简单的、一次性的函数
• 记忆口诀:lambda = 轻量级函数,用完就扔
numbers = [1, 2, 3, 4, 5]
# 普通循环写法
result = []
for n in numbers:
result.append(n * 2)
# map + lambda 写法
result = list(map(lambda x: x * 2, numbers))
print(result) # 输出:[2, 4, 6, 8, 10]
📚 讲解:
• map(函数,列表):把函数应用到每个元素
• lambda x: x * 2:匿名函数,每个元素乘 2
• list():把结果转成列表
• 适用场景:批量处理列表元素
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 普通循环写法
result = []
for n in numbers:
if n % 2 == 0:
result.append(n)
# filter + lambda 写法
result = list(filter(lambda x: x % 2 == 0, numbers))
print(result) # 输出:[2, 4, 6, 8, 10]
📚 讲解:
• filter(函数,列表):过滤符合条件的元素
• lambda x: x % 2 == 0:偶数
• 结果是一个迭代器,用 list() 转成列表
• 适用场景:过滤列表中的元素
data = [
{'name': '小明', 'score': 85},
{'name': '小红', 'score': 92},
{'name': '小刚', 'score': 78},
]
# 按分数降序排序
sorted_data = sorted(data, key=lambda x: x['score'], reverse=True)
print(sorted_data)
📚 讲解:
• sorted(列表,key=函数):按函数返回值排序
• lambda x: x['score']:按分数排序
• reverse=True:降序
• 重要:sorted + lambda 是排序的标准写法
api_response = {
'choices': [
{'text': '答案 1', 'score': 0.9},
{'text': '答案 2', 'score': 0.8},
{'text': '答案 3', 'score': 0.7},
]
}
# 提取所有文本
texts = [choice['text'] for choice in api_response['choices']]
# 过滤高分答案
high_scores = [c for c in api_response['choices'] if c['score'] > 0.8]
print(texts) # ['答案 1', '答案 2', '答案 3']
print(high_scores) # [{'text': '答案 1', 'score': 0.9}]
keywords = [' Python ', 'python', 'PYTHON', 'Java', ' java ']
# 去空格、转小写、去重
cleaned = list(set(k.strip().lower() for k in keywords))
print(cleaned) # ['python', 'java']
📚 代码讲解:
• k.strip():去空格
• .lower():转小写
• set():去重
• 生成器表达式 + set() 是去重标准写法
logs = [
{'endpoint': '/chat', 'duration': 1.2},
{'endpoint': '/chat', 'duration': 0.8},
{'endpoint': '/image', 'duration': 2.5},
{'endpoint': '/chat', 'duration': 1.5},
]
from collections import Counter
# 统计接口调用次数
endpoint_counts = Counter(log['endpoint'] for log in logs)
# 计算平均耗时
avg_duration = sum(log['duration'] for log in logs) len(logs)
print(endpoint_counts) # Counter({'/chat': 3, '/image': 1})
print(avg_duration) # 1.5
🔥 坑点 1 过度使用推导式
# ❌ 错误写法:条件太多,难以阅读
result = [x * 2 for x in range(100) if x % 2 == 0 if x > 50 if x < 80]
# ✅ 正确写法:复杂逻辑用普通循环
result = []
for x in range(100):
if x % 2 == 0 and 50 < x < 80:
result.append(x * 2)
真实案例:有同事写了个 3 层嵌套的推导式,没人看得懂——最后重构成了普通循环。
💡 建议:推导式超过 2 个条件,就用普通循环
⚠️ 坑点 2 lambda 太复杂
# ❌ 错误写法:lambda 逻辑太复杂
func = lambda x, y: x + y if x > 0 else y - x if y > 0 else 0
# ✅ 正确写法:复杂逻辑用 def
def func(x, y):
if x > 0:
return x + y
elif y > 0:
return y - x
else:
return 0
💡 建议:lambda 只适合简单逻辑,超过 1 行就用 def
💸 坑点 3 推导式副作用
# ❌ 错误写法:推导式用于副作用
result = [print(x) for x in range(5)]
# ✅ 正确写法:副作用用普通循环
for x in range(5):
print(x)
💡 建议:推导式只用于生成列表,不要用于副作用(打印、写文件等)
Q1:推导式和 map/filter 哪个更好?
A:Pythonic 的代码优先用推导式,更直观。map/filter 适合已有函数的场景。
Q2:lambda 能替代所有 def 吗?
A:不能。lambda 只适合简单逻辑,复杂逻辑还是用 def。
Q3:推导式性能比普通循环好吗?
A:略好一点点,但差异不大。主要优势是代码简洁。
Q4:什么时候不该用推导式?
A:超过 2 个条件、有副作用、逻辑复杂时,用普通循环。
上面那个代码被说啰嗦的读者,现在用推导式优化了整个项目的代码。她把这些自动化待办、学习计划都记在「搭纸」小程序里,日程管理 + 习惯打卡,效率翻倍。
✅ 个人待办 — 把自动化脚本待办记下来
✅ 日程管理 — 规划省下来的时间
✅ 习惯打卡 — 每天学点 Python
点击下方小程序卡片「搭纸」一起来搭纸打卡学习
关注公众号,可私信进学习交流群 🎁
| 列表推导式 | ||
| 字典推导式 | ||
| lambda 基础 | ||
| map | ||
| filter | ||
| sorted + lambda | ||
| 避坑指南 |
算下来,一篇回本——
不止是代码,还有你的编程品味。✿
那个写 50 行代码被说啰嗦的读者,
后来用 1 行推导式搞定。
现在她是团队的代码规范负责人,老板让她给大家做培训。
有时候,一行代码就能改变职业形象。✿
本文是「AI 大模型入门 180 天」第 17 天内容
第 16 天:Python 数据处理:JSON + 日期时间
第 18 天:Python 面向对象基础:class 入门(明天 10 点更新)
❤️ 喜欢这篇文章?欢迎分享到朋友圈




