当前位置:首页>python>Python 高手的秘密武器:一文掌握itertools模块

Python 高手的秘密武器:一文掌握itertools模块

  • 2026-02-26 00:55:16
Python 高手的秘密武器:一文掌握itertools模块

Python 的标准库是一座冰山,大多数人只用到了露出水面的那一角。itertools 模块就藏在水下,装载着十几个看似简单、实则威力惊人的工具。很多开发者在写嵌套循环、手动累积列表、反复 zip 拼接的时候,并不知道自己正在重复造轮子——而 itertools 已经把这些轮子打磨得极为精良,并且把内存开销压缩到了极致。

本文会从原理出发,结合大量实战代码,带你把 itertools 真正吃透。

一、为什么需要 itertools?

1.1 迭代器协议与惰性求值

在理解 itertools 之前,必须先厘清一个核心概念:迭代器(Iterator)

Python 中,任何实现了 __iter__() 和 __next__() 方法的对象都是迭代器。它的核心特性是惰性求值(Lazy Evaluation)——数据不是一次性全部生成,而是被请求时才产生下一个值。

# 列表:立即在内存中构建全部数据data = [x ** 2for x in range(10_000_000)]  # 占用大量内存# 生成器:按需生成,内存占用近乎为零data = (x ** 2for x in range(10_000_000))  # 几乎不占内存

itertools 中所有函数返回的都是迭代器,而非列表。这意味着:

  • 无论输入数据多大,内存占用保持稳定;
  • 可以与其他迭代器自由组合,构建数据处理流水线;
  • 大多数操作时间复杂度为 O(1) 空间,O(n) 时间。

1.2 性能对比:为何不自己写?

import itertoolsimport time# 手动实现笛卡尔积defmanual_product(a, b):    result = []for x in a:for y in b:            result.append((x, y))return result# 使用 itertools.producta = range(1000)b = range(1000)start = time.perf_counter()list(itertools.product(a, b))print(f"itertools: {time.perf_counter() - start:.4f}s")start = time.perf_counter()manual_product(a, b)print(f"手动实现: {time.perf_counter() - start:.4f}s")

itertools 的核心函数由 C 语言实现,速度通常比纯 Python 快 2~10 倍,且无需任何额外依赖。


二、无限迭代器:永不停歇的数据源

这三个函数能产生无限序列,使用时必须配合 islice 或 break 截断,否则程序会陷入死循环。

2.1 count(start=0, step=1) — 无限计数器

import itertools# 基础用法:从10开始,步长2counter = itertools.count(102)print(list(itertools.islice(counter, 5)))  # [10, 12, 14, 16, 18]# 支持浮点步长(range 不支持)float_counter = itertools.count(0.00.1)print(list(itertools.islice(float_counter, 5)))  # [0.0, 0.1, 0.2, 0.3, 0.4]# 实战:为流式数据自动编号defauto_enumerate(iterable, start=1):"""比 enumerate 更灵活,支持自定义起始值和步长"""return zip(itertools.count(start), iterable)data = ['Alice''Bob''Charlie']for idx, name in auto_enumerate(data, start=100):    print(f"ID-{idx}{name}")# ID-100: Alice# ID-101: Bob# ID-102: Charlie

2.2 cycle(iterable) — 无限循环

# 基础:无限轮播colors = itertools.cycle(['red''green''blue'])print(list(itertools.islice(colors, 7)))# ['red', 'green', 'blue', 'red', 'green', 'blue', 'red']# 实战:负载均衡轮询调度servers = ['server-1:8001''server-2:8002''server-3:8003']scheduler = itertools.cycle(servers)defget_next_server():return next(scheduler)# 模拟10次请求分配for i in range(10):    print(f"请求 {i+1} -> {get_next_server()}")# 实战:斑马纹表格行样式defrender_table(rows):    styles = itertools.cycle(['row-even''row-odd'])for row, style in zip(rows, styles):        print(f'<tr class="{style}">{row}</tr>')

2.3 repeat(object, times=None) — 重复生成

# 有限重复print(list(itertools.repeat('X'5)))  # ['X', 'X', 'X', 'X', 'X']# 与 map 结合:替代 lambda 中的固定参数import operator# 计算 2^0, 2^1, 2^2, 2^3, 2^4powers = list(map(operator.pow, itertools.repeat(25), range(5)))print(powers)  # [1, 2, 4, 8, 16]# 实战:并行初始化多个对象from collections import defaultdictdefcreate_empty_lists(n):"""创建 n 个独立的空列表(注意:不能用 [[]]*n,那会引用同一个列表)"""return list(itertools.repeat(None, n))

三、有限迭代器:数据处理流水线的核心

3.1 islice — 迭代器版的切片

islice 是操作无限迭代器时不可缺少的利器。

# 语法:islice(iterable, stop) 或 islice(iterable, start, stop[, step])counter = itertools.count(0)# 取前10个print(list(itertools.islice(counter, 10)))  # [0, 1, 2, ..., 9]# 跳过前5个,取接下来的5个counter2 = itertools.count(0)print(list(itertools.islice(counter2, 510)))  # [5, 6, 7, 8, 9]# 实战:分批处理大文件defread_in_batches(iterable, batch_size):"""将任意可迭代对象按批次读取,不将全部数据加载进内存"""    it = iter(iterable)whileTrue:        batch = list(itertools.islice(it, batch_size))ifnot batch:breakyield batch# 处理海量日志文件with open('large_log.txt''r'as f:for batch in read_in_batches(f, batch_size=1000):# 每次处理 1000 行,内存始终只有 1000 行的数据        process(batch)

3.2 chain 与 chain.from_iterable — 序列拼接

# 基础拼接result = list(itertools.chain([12], [34], [56]))print(result)  # [1, 2, 3, 4, 5, 6]# 展平嵌套列表(一层)nested = [[123], [45], [6789]]flat = list(itertools.chain.from_iterable(nested))print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]# 对比:sum([[1,2],[3,4]], []) 也能展平,但性能极差# chain.from_iterable 是 O(n) 时间、O(1) 空间,sum 是 O(n²)# 实战:合并多个数据库查询结果defmerge_query_results(*result_sets):"""将多个查询结果集合并为单一迭代器,无需构建中间列表"""return itertools.chain.from_iterable(result_sets)# 实战:字符串展平words = ['hello''world']chars = list(itertools.chain.from_iterable(words))print(chars)  # ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

3.3 compress — 按掩码筛选

# 根据布尔掩码选取数据data    = ['A''B''C''D''E''F']selectors = [1,   0,   1,   0,   1,   1]result = list(itertools.compress(data, selectors))print(result)  # ['A', 'C', 'E', 'F']# 实战:根据特征向量筛选样本features = [0.80.20.90.10.70.3]samples  = ['s1''s2''s3''s4''s5''s6']threshold = 0.5# 筛选置信度超过阈值的样本high_conf_samples = list(    itertools.compress(samples, (f > threshold for f in features)))print(high_conf_samples)  # ['s1', 's3', 's5']

3.4 dropwhile 与 takewhile — 基于条件的截取

data = [12310456]# takewhile:条件为真时持续取值,一旦为假立即停止result = list(itertools.takewhile(lambda x: x < 5, data))print(result)  # [1, 2, 3]  注意:10 < 5 为假,后续的 4,5,6 也不会被取到# dropwhile:条件为真时持续跳过,一旦为假立即开始取值result = list(itertools.dropwhile(lambda x: x < 5, data))print(result)  # [10, 4, 5, 6]# 实战:跳过日志文件头部注释defskip_comments(lines):"""跳过以 '#' 开头的注释行,从第一个有效行开始读取"""return itertools.dropwhile(lambda line: line.startswith('#'), lines)log_lines = ['# version: 1.0''# author: admin''2024-01-01 ERROR ...''2024-01-02 INFO ...']for line in skip_comments(log_lines):    print(line)# 2024-01-01 ERROR ...# 2024-01-02 INFO ...

3.5 filterfalse — 反向过滤

# 与 filter 相反:保留使函数返回 False 的元素data = range(10)odd_numbers = list(itertools.filterfalse(lambda x: x % 2 == 0, data))print(odd_numbers)  # [1, 3, 5, 7, 9]# 实战:将数据集拆分为两组defpartition(pred, iterable):"""将可迭代对象按条件分割为两个迭代器"""    t1, t2 = itertools.tee(iterable)return filter(pred, t1), itertools.filterfalse(pred, t2)evens, odds = partition(lambda x: x % 2 == 0, range(10))print(list(evens))  # [0, 2, 4, 6, 8]print(list(odds))   # [1, 3, 5, 7, 9]

3.6 starmap — 解包参数的 map

# map(func, iterable) 的增强版,自动解包元组参数data = [(23), (42), (103)]# 等价于 [2**3, 4**2, 10**3],但更简洁result = list(itertools.starmap(pow, data))print(result)  # [8, 16, 1000]# 实战:批量计算欧氏距离import mathpoints = [(0011), (1246), (0034)]distances = list(itertools.starmap(lambda x1, y1, x2, y2: math.hypot(x2 - x1, y2 - y1),    points))print(distances)  # [1.414..., 5.0, 5.0]

3.7 zip_longest — 对齐不等长序列

from itertools import zip_longesta = [12345]b = ['a''b''c']# 内置 zip 以最短序列为准,会丢弃数据print(list(zip(a, b)))  # [(1, 'a'), (2, 'b'), (3, 'c')]# zip_longest 以最长序列为准,缺失值用 fillvalue 填充print(list(zip_longest(a, b, fillvalue='?')))# [(1, 'a'), (2, 'b'), (3, 'c'), (4, '?'), (5, '?')]# 实战:合并多个时间序列数据(可能长度不一致)defmerge_time_series(*series, fill=None):return list(zip_longest(*series, fillvalue=fill))

3.8 pairwise(Python 3.10+)— 相邻元素对

# 生成相邻元素对,常用于差值计算data = [1361015]diffs = [b - a for a, b in itertools.pairwise(data)]print(diffs)  # [2, 3, 4, 5]# 实战:检测价格异常波动prices = [10010298150103]  # 150 是异常值threshold = 20anomalies = [    (i+1, prev, curr)for i, (prev, curr) in enumerate(itertools.pairwise(prices))if abs(curr - prev) > threshold]print(anomalies)  # [(3, 98, 150)]

3.9 accumulate — 累积计算

import operatordata = [12345]# 默认:累积求和(类似 numpy.cumsum)print(list(itertools.accumulate(data)))  # [1, 3, 6, 10, 15]# 自定义运算:累积乘积print(list(itertools.accumulate(data, operator.mul)))  # [1, 2, 6, 24, 120]# 自定义运算:滚动最大值print(list(itertools.accumulate(data, max)))  # [1, 2, 3, 4, 5]data2 = [31415926]print(list(itertools.accumulate(data2, max)))  # [3, 3, 4, 4, 5, 9, 9, 9]# 实战:计算投资组合的资产净值曲线daily_returns = [0.01-0.020.0150.008-0.005]initial_nav = 1.0nav_curve = list(itertools.accumulate(    daily_returns,lambda nav, r: nav * (1 + r),    initial=initial_nav))print([f"{v:.4f}"for v in nav_curve])# ['1.0000', '1.0100', '0.9898', '1.0046', '1.0127', '1.0076']

四、组合迭代器:排列、组合、笛卡尔积

这四个函数是 itertools 中知名度最高的,广泛应用于算法竞赛、搜索空间枚举、密码破解、测试用例生成等场景。

4.1 product — 笛卡尔积

# 两个序列的笛卡尔积(等价于双重嵌套循环)result = list(itertools.product('AB', [123]))print(result)# [('A', 1), ('A', 2), ('A', 3), ('B', 1), ('B', 2), ('B', 3)]# repeat 参数:自身的笛卡尔积# 等价于 product('AB', 'AB')result = list(itertools.product('AB', repeat=2))print(result)# [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]# 实战:生成所有可能的超参数组合(网格搜索)learning_rates = [0.0010.010.1]batch_sizes    = [3264128]optimizers     = ['adam''sgd']param_grid = list(itertools.product(learning_rates, batch_sizes, optimizers))print(f"共 {len(param_grid)} 种超参数组合")  # 共 18 种超参数组合for lr, bs, opt in param_grid:# train_model(lr=lr, batch_size=bs, optimizer=opt)pass# 实战:枚举密码空间(仅用于授权测试)import stringchars = string.digits + string.ascii_lowercase# 生成所有 4 位密码(不实际存储,节省内存)passwords = itertools.product(chars, repeat=4)# 总数:36^4 = 1,679,616 种,但内存只存当前一个

4.2 permutations — 全排列

# n 个元素取 r 个的全排列(有序)# 总数:P(n, r) = n! / (n-r)!result = list(itertools.permutations('ABC'2))print(result)# [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]# r 默认为全部元素all_perms = list(itertools.permutations([123]))print(len(all_perms))  # 6,即 3!# 实战:寻找最优访问顺序(旅行商问题的暴力解法)import mathcities = {'A': (00), 'B': (13), 'C': (41), 'D': (24)}defdistance(c1, c2):    x1, y1 = cities[c1]    x2, y2 = cities[c2]return math.hypot(x2 - x1, y2 - y1)deftotal_distance(route):return sum(distance(route[i], route[i+1]) for i in range(len(route)-1))city_names = list(cities.keys())best_route = min(    itertools.permutations(city_names[1:]),  # 固定起点A    key=lambda p: total_distance(['A'] + list(p) + ['A']))print(f"最优路径:A -> {' -> '.join(best_route)} -> A")

4.3 combinations — 组合

# n 个元素取 r 个的组合(无序,不重复)# 总数:C(n, r) = n! / (r! * (n-r)!)result = list(itertools.combinations('ABCD'2))print(result)# [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]# 实战:生成所有可能的特征子集(特征选择)features = ['age''income''education''credit_score']for r in range(1, len(features) + 1):for combo in itertools.combinations(features, r):# evaluate_model(feature_subset=combo)        print(f"测试特征子集: {combo}")# 实战:计算所有股票对之间的相关性import randomstocks = ['AAPL''GOOG''MSFT''AMZN''META']correlations = {}for s1, s2 in itertools.combinations(stocks, 2):    correlations[(s1, s2)] = round(random.uniform(-11), 3)  # 模拟相关系数# 找出相关性最高的股票对most_correlated = max(correlations, key=correlations.get)print(f"相关性最高: {most_correlated} = {correlations[most_correlated]}")

4.4 combinations_with_replacement — 有放回组合

# 与 combinations 的区别:同一个元素可以被选多次result = list(itertools.combinations_with_replacement('ABC'2))print(result)# [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]# 实战:生成多项式的所有项(给定变量和最高次数)# 比如 x, y 的 2 次多项式所有单项式:x², xy, y², x, y, 常数variables = ['x''y']max_degree = 2monomials = []for degree in range(max_degree + 1):for combo in itertools.combinations_with_replacement(variables, degree):        monomials.append(combo)print(monomials)# [(), ('x',), ('y',), ('x', 'x'), ('x', 'y'), ('y', 'y')]

五、分组迭代器:groupby

groupby 是 itertools 中最容易被误用的函数,必须先排序后分组。

# 基础用法data = [('A'1), ('A'2), ('B'3), ('B'4), ('C'5)]# ⚠️ 关键:groupby 只对连续相同的键进行分组# 必须先按键排序!for key, group in itertools.groupby(data, key=lambda x: x[0]):    print(f"{key}{list(group)}")# A: [('A', 1), ('A', 2)]# B: [('B', 3), ('B', 4)]# C: [('C', 5)]# 常见错误:不排序导致意外分组unordered = [('A'1), ('B'2), ('A'3)]  # A 不连续for key, group in itertools.groupby(unordered, key=lambda x: x[0]):    print(f"{key}{list(group)}")# A: [('A', 1)]   ← A 被分割成两组,不符合预期# B: [('B', 2)]# A: [('A', 3)]# ✅ 正确做法from operator import itemgetterunordered = [('A'1), ('B'2), ('A'3)]sorted_data = sorted(unordered, key=itemgetter(0))for key, group in itertools.groupby(sorted_data, key=itemgetter(0)):    print(f"{key}{list(group)}")# A: [('A', 1), ('A', 3)]# B: [('B', 2)]# 实战:日志文件按日期聚合分析import datetimelogs = [    {'date''2024-01-01''level''ERROR''msg''DB timeout'},    {'date''2024-01-01''level''INFO',  'msg''Server start'},    {'date''2024-01-02''level''ERROR''msg''Out of memory'},    {'date''2024-01-02''level''WARN',  'msg''High CPU'},    {'date''2024-01-02''level''ERROR''msg''Disk full'},]logs.sort(key=itemgetter('date'))for date, entries in itertools.groupby(logs, key=itemgetter('date')):    entries_list = list(entries)    error_count = sum(1for e in entries_list if e['level'] == 'ERROR')    print(f"{date}: 共 {len(entries_list)} 条日志,其中 {error_count} 条错误")# 实战:RLE 游程编码defrun_length_encode(s):"""将字符串进行 RLE 编码:'AAABBBCCCA' -> [(A,3),(B,3),(C,3),(A,1)]"""return [(char, len(list(group))) for char, group in itertools.groupby(s)]print(run_length_encode('AAABBBCCCA'))# [('A', 3), ('B', 3), ('C', 3), ('A', 1)]

六、tee — 迭代器的克隆

# 将一个迭代器复制为 n 个独立的迭代器a, b = itertools.tee([12345], 2)print(list(a))  # [1, 2, 3, 4, 5]print(list(b))  # [1, 2, 3, 4, 5]# ⚠️ 重要警告:tee 会在内存中缓存数据# 如果两个迭代器消费速度差异很大,内存占用会显著增加# 如果需要多次遍历,直接用 list() 转换通常更高效# 实战:同时计算均值和方差(单次遍历)defmean_and_variance(iterable):"""只遍历一次数据,同时计算均值和方差"""    a, b = itertools.tee(iterable)    values = list(a)    n = len(values)    mean = sum(values) / n    variance = sum((x - mean) ** 2for x in b) / nreturn mean, variancedata = [24445579]mean, var = mean_and_variance(data)print(f"均值: {mean}, 方差: {var}")  # 均值: 5.0, 方差: 4.0

七、构建复杂数据处理流水线

itertools 真正的威力,在于将多个函数链式组合,构建出既高效又内存友好的数据处理管道。

import itertoolsimport csvfrom operator import itemgetter# 场景:处理一个超大 CSV 文件# 需求:跳过前5行注释,过滤出金额>1000的交易,#       按用户ID分组,计算每个用户的总消费额defprocess_large_csv(filepath):with open(filepath, 'r'as f:        reader = csv.DictReader(f)# 步骤1:过滤掉无效行        valid_rows = filter(lambda r: r.get('amount'), reader)# 步骤2:过滤金额>1000的交易        high_value = filter(lambda r: float(r['amount']) > 1000, valid_rows)# 步骤3:转换数据类型        parsed = (            {'user_id': r['user_id'], 'amount': float(r['amount'])}for r in high_value        )# 步骤4:按用户ID排序(groupby 的前提)        sorted_data = sorted(parsed, key=itemgetter('user_id'))# 步骤5:按用户分组,统计总消费        results = {}for user_id, transactions in itertools.groupby(sorted_data, key=itemgetter('user_id')):            total = sum(t['amount'for t in transactions)            results[user_id] = totalreturn results# 场景:生成测试数据集defgenerate_test_cases(param_space: dict):"""    根据参数空间字典生成所有测试用例    param_space = {'lr': [0.01, 0.1], 'epoch': [10, 50], 'dropout': [0.1, 0.5]}    """    keys = list(param_space.keys())    values = list(param_space.values())for combination in itertools.product(*values):yield dict(zip(keys, combination))param_space = {'lr':      [0.0010.010.1],'epoch':   [50100],'dropout': [0.10.30.5],}test_cases = list(generate_test_cases(param_space))print(f"生成 {len(test_cases)} 个测试用例")  # 18 个print(test_cases[0])  # {'lr': 0.001, 'epoch': 50, 'dropout': 0.1}

八、itertools 的性能陷阱与最佳实践

8.1 tee 的内存泄漏风险

# ❌ 危险:两个迭代器消费速度差距很大a, b = itertools.tee(range(10_000_000))list(a)   # 全部消费 anext(b)   # b 还没消费,内存中已缓存了近 10M 个元素!# ✅ 建议:如果需要多次遍历,直接转换为 listdata = list(range(10_000_000))  # 明确的内存使用,可控

8.2 groupby 中的 group 对象不可复用

# ❌ 错误:group 对象使用后会失效data = [('A'1), ('A'2), ('B'3)]data.sort(key=itemgetter(0))groups = {}for key, group in itertools.groupby(data, key=itemgetter(0)):    groups[key] = group  # 这里的 group 是迭代器,不是列表!# 此时再访问 groups['A'] 可能得到空迭代器(已被内部推进)# ✅ 正确:立即将 group 转换为 listgroups = {}for key, group in itertools.groupby(data, key=itemgetter(0)):    groups[key] = list(group)  # 立即物化

8.3 组合函数的数量爆炸问题

# permutations(range(15)) 会产生 15! = 1,307,674,368,000 个元素# 永远不要对大集合调用 list()n = 15print(f"permutations({n}) 的总数: {math.factorial(n):,}")# 1,307,674,368,000 — 遍历完需要数小时甚至数天# ✅ 正确:只取需要的部分first_10 = list(itertools.islice(itertools.permutations(range(15)), 10))

九、与 functoolsoperator 的协同使用

itertools 与 functools 和 operator 模块配合时,能写出极为简洁高效的代码。

import functoolsimport operator# 使用 operator 模块代替 lambda(性能更好)data = [(1'a'), (3'c'), (2'b')]sorted_data = sorted(data, key=operator.itemgetter(0))# functools.reduce + itertools.chain 展平并求积nested = [[123], [45], [6]]flat = list(itertools.chain.from_iterable(nested))product = functools.reduce(operator.mul, flat, 1)print(f"所有元素之积: {product}")  # 720# 构建高阶函数:带滑动窗口的 mapdefwindowed_map(func, iterable, window_size):"""对序列中每个滑动窗口应用函数"""    iters = itertools.tee(iterable, window_size)# 将每个迭代器偏移 i 步for i, it in enumerate(iters):        next(itertools.islice(it, i, i), None)  # 快进 i 步    windows = zip(*iters)return map(func, windows)data = [123456]# 对每个长度为3的窗口求和window_sums = list(windowed_map(sum, data, 3))print(window_sums)  # [6, 9, 12, 15]  即 (1+2+3), (2+3+4), (3+4+5), (4+5+6)

十、案例:用 itertools 实现高效的数据分析及处理

"""场景:电商平台订单数据分析需求:从海量订单中找出 VIP 用户(总消费 > 10000),      统计他们最常购买的商品类别,输出 Top 3"""import itertoolsimport randomfrom collections import Counterfrom operator import itemgetter# 模拟海量订单数据(生成器,不占内存)defgenerate_orders(n=1_000_000):    users = [f'user_{i:04d}'for i in range(100)]    categories = ['电子''服装''食品''图书''家居''运动']for _ in range(n):yield {'user_id': random.choice(users),'amount': round(random.uniform(10500), 2),'category': random.choice(categories)        }defanalyze_vip_preferences(orders_gen):# 步骤1:按用户ID排序(需要物化,因为排序无法惰性执行)# 实际生产中应从已排序的数据库查询获取    print("正在排序数据...")    sorted_orders = sorted(orders_gen, key=itemgetter('user_id'))# 步骤2:按用户分组,筛选 VIP    print("正在筛选 VIP 用户...")    vip_categories = {}for user_id, user_orders in itertools.groupby(sorted_orders, key=itemgetter('user_id')):        orders_list = list(user_orders)        total_spent = sum(o['amount'for o in orders_list)if total_spent > 10000:  # VIP 门槛# 统计该用户的类别偏好            category_counts = Counter(o['category'for o in orders_list)            vip_categories[user_id] = {'total_spent': round(total_spent, 2),'top_categories': category_counts.most_common(3)            }return vip_categories# 运行分析orders = generate_orders(100_000)  # 10万条订单vip_data = analyze_vip_preferences(orders)print(f"\n共发现 {len(vip_data)} 位 VIP 用户")for user_id, info in list(vip_data.items())[:3]:    print(f"\n{user_id}: 总消费 ¥{info['total_spent']}")for cat, count in info['top_categories']:        print(f"  {cat}{count} 次")

总结

itertools 是 Python 标准库中设计最为精良的模块之一。它的核心价值体现在三个层面:

第一,底层操作层面:拥抱惰性求值,将数据处理从"搬运大箱子"变成"开水龙头按需取水",从根本上改变了对内存和时间的消耗方式。

第二,工程层面:所有函数由 C 实现,速度远超等价的纯 Python 代码;函数之间可以任意组合,构建出清晰、可维护的数据处理管道。

第三,表达层面:一行 itertools.groupby 替代二十行嵌套循环,代码的意图变得一目了然。好的代码不仅告诉机器"怎么做",更告诉读者"做什么"。

掌握 itertools,意味着你开始以"流"的方式思考数据,而不是"块"。这不仅是一个模块的学习,更是一次编程思维的升级。

最新文章

随机文章

基本 文件 流程 错误 SQL 调试
  1. 请求信息 : 2026-03-01 08:23:23 HTTP/2.0 GET : https://f.mffb.com.cn/a/476746.html
  2. 运行时间 : 0.078147s [ 吞吐率:12.80req/s ] 内存消耗:4,701.84kb 文件加载:140
  3. 缓存信息 : 0 reads,0 writes
  4. 会话信息 : SESSION_ID=6b9f097d81567fc0977e9ad76fbf463e
  1. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/public/index.php ( 0.79 KB )
  2. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/autoload.php ( 0.17 KB )
  3. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_real.php ( 2.49 KB )
  4. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/platform_check.php ( 0.90 KB )
  5. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/ClassLoader.php ( 14.03 KB )
  6. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_static.php ( 4.90 KB )
  7. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper.php ( 8.34 KB )
  8. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/helper.php ( 2.19 KB )
  9. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/helper.php ( 1.47 KB )
  10. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/stubs/load_stubs.php ( 0.16 KB )
  11. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Exception.php ( 1.69 KB )
  12. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Facade.php ( 2.71 KB )
  13. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/deprecation-contracts/function.php ( 0.99 KB )
  14. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap.php ( 8.26 KB )
  15. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap80.php ( 9.78 KB )
  16. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/Resources/functions/dump.php ( 1.49 KB )
  17. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-dumper/src/helper.php ( 0.18 KB )
  18. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/VarDumper.php ( 4.30 KB )
  19. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/App.php ( 15.30 KB )
  20. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Container.php ( 15.76 KB )
  21. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/container/src/ContainerInterface.php ( 1.02 KB )
  22. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/provider.php ( 0.19 KB )
  23. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Http.php ( 6.04 KB )
  24. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Str.php ( 7.29 KB )
  25. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Env.php ( 4.68 KB )
  26. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/common.php ( 0.03 KB )
  27. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/helper.php ( 18.78 KB )
  28. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Config.php ( 5.54 KB )
  29. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/app.php ( 0.95 KB )
  30. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cache.php ( 0.78 KB )
  31. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/console.php ( 0.23 KB )
  32. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cookie.php ( 0.56 KB )
  33. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/database.php ( 2.48 KB )
  34. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Env.php ( 1.67 KB )
  35. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/filesystem.php ( 0.61 KB )
  36. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/lang.php ( 0.91 KB )
  37. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/log.php ( 1.35 KB )
  38. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/middleware.php ( 0.19 KB )
  39. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/route.php ( 1.89 KB )
  40. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/session.php ( 0.57 KB )
  41. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/trace.php ( 0.34 KB )
  42. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/view.php ( 0.82 KB )
  43. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/event.php ( 0.25 KB )
  44. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Event.php ( 7.67 KB )
  45. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/service.php ( 0.13 KB )
  46. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/AppService.php ( 0.26 KB )
  47. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Service.php ( 1.64 KB )
  48. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Lang.php ( 7.35 KB )
  49. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/lang/zh-cn.php ( 13.70 KB )
  50. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/Error.php ( 3.31 KB )
  51. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/RegisterService.php ( 1.33 KB )
  52. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/services.php ( 0.14 KB )
  53. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/PaginatorService.php ( 1.52 KB )
  54. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ValidateService.php ( 0.99 KB )
  55. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ModelService.php ( 2.04 KB )
  56. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Service.php ( 0.77 KB )
  57. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Middleware.php ( 6.72 KB )
  58. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/BootService.php ( 0.77 KB )
  59. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Paginator.php ( 11.86 KB )
  60. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/Validate.php ( 63.20 KB )
  61. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Model.php ( 23.55 KB )
  62. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Attribute.php ( 21.05 KB )
  63. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/AutoWriteData.php ( 4.21 KB )
  64. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Conversion.php ( 6.44 KB )
  65. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/DbConnect.php ( 5.16 KB )
  66. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/ModelEvent.php ( 2.33 KB )
  67. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/RelationShip.php ( 28.29 KB )
  68. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Arrayable.php ( 0.09 KB )
  69. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Jsonable.php ( 0.13 KB )
  70. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/contract/Modelable.php ( 0.09 KB )
  71. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Db.php ( 2.88 KB )
  72. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/DbManager.php ( 8.52 KB )
  73. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Log.php ( 6.28 KB )
  74. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Manager.php ( 3.92 KB )
  75. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerTrait.php ( 2.69 KB )
  76. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerInterface.php ( 2.71 KB )
  77. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cache.php ( 4.92 KB )
  78. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/simple-cache/src/CacheInterface.php ( 4.71 KB )
  79. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Arr.php ( 16.63 KB )
  80. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/driver/File.php ( 7.84 KB )
  81. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/Driver.php ( 9.03 KB )
  82. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/CacheHandlerInterface.php ( 1.99 KB )
  83. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/Request.php ( 0.09 KB )
  84. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Request.php ( 55.78 KB )
  85. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/middleware.php ( 0.25 KB )
  86. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Pipeline.php ( 2.61 KB )
  87. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/TraceDebug.php ( 3.40 KB )
  88. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/middleware/SessionInit.php ( 1.94 KB )
  89. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Session.php ( 1.80 KB )
  90. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/driver/File.php ( 6.27 KB )
  91. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/SessionHandlerInterface.php ( 0.87 KB )
  92. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/Store.php ( 7.12 KB )
  93. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Route.php ( 23.73 KB )
  94. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleName.php ( 5.75 KB )
  95. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Domain.php ( 2.53 KB )
  96. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleGroup.php ( 22.43 KB )
  97. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Rule.php ( 26.95 KB )
  98. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleItem.php ( 9.78 KB )
  99. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/route/app.php ( 1.72 KB )
  100. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Route.php ( 4.70 KB )
  101. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/dispatch/Controller.php ( 4.74 KB )
  102. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Dispatch.php ( 10.44 KB )
  103. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/controller/Index.php ( 4.81 KB )
  104. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/BaseController.php ( 2.05 KB )
  105. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/facade/Db.php ( 0.93 KB )
  106. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/connector/Mysql.php ( 5.44 KB )
  107. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/PDOConnection.php ( 52.47 KB )
  108. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Connection.php ( 8.39 KB )
  109. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/ConnectionInterface.php ( 4.57 KB )
  110. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/builder/Mysql.php ( 16.58 KB )
  111. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Builder.php ( 24.06 KB )
  112. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseBuilder.php ( 27.50 KB )
  113. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Query.php ( 15.71 KB )
  114. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseQuery.php ( 45.13 KB )
  115. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TimeFieldQuery.php ( 7.43 KB )
  116. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/AggregateQuery.php ( 3.26 KB )
  117. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ModelRelationQuery.php ( 20.07 KB )
  118. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ParamsBind.php ( 3.66 KB )
  119. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ResultOperation.php ( 7.01 KB )
  120. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/WhereQuery.php ( 19.37 KB )
  121. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/JoinAndViewQuery.php ( 7.11 KB )
  122. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TableFieldInfo.php ( 2.63 KB )
  123. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/Transaction.php ( 2.77 KB )
  124. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/driver/File.php ( 5.96 KB )
  125. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/LogHandlerInterface.php ( 0.86 KB )
  126. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/Channel.php ( 3.89 KB )
  127. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/event/LogRecord.php ( 1.02 KB )
  128. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/Collection.php ( 16.47 KB )
  129. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/View.php ( 1.70 KB )
  130. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/View.php ( 4.39 KB )
  131. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Response.php ( 8.81 KB )
  132. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/response/View.php ( 3.29 KB )
  133. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cookie.php ( 6.06 KB )
  134. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-view/src/Think.php ( 8.38 KB )
  135. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/TemplateHandlerInterface.php ( 1.60 KB )
  136. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/Template.php ( 46.61 KB )
  137. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/driver/File.php ( 2.41 KB )
  138. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/contract/DriverInterface.php ( 0.86 KB )
  139. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/runtime/temp/067d451b9a0c665040f3f1bdd3293d68.php ( 11.98 KB )
  140. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Html.php ( 4.42 KB )
  1. CONNECT:[ UseTime:0.000477s ] mysql:host=127.0.0.1;port=3306;dbname=f_mffb;charset=utf8mb4
  2. SHOW FULL COLUMNS FROM `fenlei` [ RunTime:0.000663s ]
  3. SELECT * FROM `fenlei` WHERE `fid` = 0 [ RunTime:0.000255s ]
  4. SELECT * FROM `fenlei` WHERE `fid` = 63 [ RunTime:0.000501s ]
  5. SHOW FULL COLUMNS FROM `set` [ RunTime:0.000469s ]
  6. SELECT * FROM `set` [ RunTime:0.000197s ]
  7. SHOW FULL COLUMNS FROM `article` [ RunTime:0.000582s ]
  8. SELECT * FROM `article` WHERE `id` = 476746 LIMIT 1 [ RunTime:0.000986s ]
  9. UPDATE `article` SET `lasttime` = 1772324603 WHERE `id` = 476746 [ RunTime:0.001726s ]
  10. SELECT * FROM `fenlei` WHERE `id` = 66 LIMIT 1 [ RunTime:0.000310s ]
  11. SELECT * FROM `article` WHERE `id` < 476746 ORDER BY `id` DESC LIMIT 1 [ RunTime:0.000420s ]
  12. SELECT * FROM `article` WHERE `id` > 476746 ORDER BY `id` ASC LIMIT 1 [ RunTime:0.000547s ]
  13. SELECT * FROM `article` WHERE `id` < 476746 ORDER BY `id` DESC LIMIT 10 [ RunTime:0.001934s ]
  14. SELECT * FROM `article` WHERE `id` < 476746 ORDER BY `id` DESC LIMIT 10,10 [ RunTime:0.000837s ]
  15. SELECT * FROM `article` WHERE `id` < 476746 ORDER BY `id` DESC LIMIT 20,10 [ RunTime:0.001112s ]
0.079649s