【Python 语法糖小火锅 · 第 4 涮】

一、糖味一句话

列表 / 集合 / 字典 / 生成器推导式 = 把「循环 + 条件 + 收集」三件套浓缩成一行,

编译器帮你做 append、add、update,速度还更快。


二、1 行示例 4 连发

python 复制代码
nums = range(10)

lst = [x*x for x in nums if x % 2 == 0]          # 列表
s   = {x for x in nums if x > 5}                 # 集合
d   = {x: x**3 for x in nums if x < 4}           # 字典
gen = (x for x in nums if x % 3)                 # 生成器(惰性)

三、真实场景:日志字段秒变字典

需求:从 access.log 里提取所有状态码 ≥ 400 的 IP 并去重计数。

python 复制代码
from pathlib import Path
from collections import Counter

ips_4xx = Counter(
    line.split()[0]
    for line in Path('access.log').read_text().splitlines()
    if len(line.split()) > 8 and int(line.split()[8]) >= 400
)
print(ips_4xx.most_common(5))

全程只用 1 个推导式 + 1 个 Counter,无显式循环。


四、防踩坑小贴士

  1. 列表推导式会一次性生成全部元素,大数据请改用生成器表达式
  2. 不要在推导式里写副作用(print、append),会失去可读性。
  3. 嵌套推导式尽量拆成两步,否则调试时找不到北。

记忆口令 :"中括号列表,花括号集/字典,圆括号生万物; for 在前 if 在后,一行循环不用愁。"