当前位置:首页>python>Python 数据处理常用函数介绍:map、filter、reduce 、itertools 等

Python 数据处理常用函数介绍:map、filter、reduce 、itertools 等

  • 2026-10-11 06:48:23
Python 数据处理常用函数介绍:map、filter、reduce 、itertools 等

列表推导式是 Python 数据处理的瑞士军刀——简洁、直观、可读性好。但在实际项目中,你迟早会遇到它力不从心的场景:处理多个可迭代对象的并行映射、对无限序列做延迟计算、构建多层嵌套的笛卡尔积、或者对数据集做分页切片。这些场景下,Python 内置的 map、filter、reduce 与 itertools 模块提供了更优的解法。

本文不讨论函数式编程的纯理论,而是聚焦于日常数据处理中最实用的函数式工具,通过代码对比展示它们的适用边界与取舍策略。

一、map:不仅仅是批量映射

基础用法

map 将一个函数批量应用到可迭代对象的每个元素上,返回一个惰性迭代器。

nums = [1, 2, 3, 4, 5]squared = []for n in nums:    squared.append(n ** 2)squared = list(map(lambda x: x ** 2, nums))

多可迭代对象并行处理

map 的真正优势在于同时处理多个可迭代对象,这是列表推导式做不到的:

prices = [100, 200, 300]quantities = [3, 5, 2]totals = [p * q for p, q in zip(prices, quantities)]totals = list(map(lambda p, q: p * q, prices, quantities))

当需要处理 3 个及以上可迭代对象时,map 的简洁度优势更明显:

prices = [100, 200, 300]quantities = [3, 5, 2]discounts = [0.9, 0.85, 0.95]totals = list(map(lambda p, q, d: p * q * d, prices, quantities, discounts))

性能实测

map 比等价的列表推导式略快,因为避免了 Python 字节码的循环开销:

import timeitprint(timeit.timeit('list(map(lambda x: x**2, range(10000)))', number=1000))print(timeit.timeit('[x**2 for x in range(10000)]', number=1000))

实测结果:map 通常快 10-20%。但不要为了性能而牺牲可读性——在简单场景下,列表推导式仍是更 Pythonic 的选择。

二、filter:精准筛选的两种姿势

filter 用布尔函数筛选可迭代对象,同样返回惰性迭代器。

nums = range(-10, 11)positive = []for n in nums:    if n > 0:        positive.append(n)positive = list(filter(lambda x: x > 0, nums))

filter vs 推导式条件过滤

result1 = list(filter(lambda x: x % 2 == 0, range(100)))result2 = [x for x in range(100) if x % 2 == 0]

选择建议:当筛选条件是一个已存在的函数时,filter 可读性更高:

def is_valid_record(row: dict) -> bool:    return row.get("status") == "active" and row.get("amount", 0) > 0valid = list(filter(is_valid_record, records))      # 清晰valid = [r for r in records if is_valid_record(r)]  # 略显冗余

三、reduce:累积计算

reduce 位于 functools 模块,它将一个二元函数累积地应用到序列的元素上,逐步归约为单个值。

从累加开始

from functools import reducetotal = reduce(lambda a, b: a + b, [1, 2, 3, 4, 5])  # 15

进阶:嵌套字典合并

dicts = [    {"a": 1, "b": 2},    {"b": 3, "c": 4},    {"d": 5},]merged = reduce(lambda acc, d: {**acc, **d}, dicts, {})

案例:分组统计

from collections import defaultdictfrom functools import reducedata = [    ("A", 100), ("B", 200), ("A", 150),    ("C", 300), ("B", 50),  ("A", 80),]def group_sum(acc, item):    key, val = item    acc[key] = acc.get(key, 0) + val    return accresult = reduce(group_sum, data, {})

何时不用 reduce

Python 有专门的内置函数替代常见的 reduce 场景:

reduce(lambda a, b: a + b, nums)  # ❌sum(nums)                          # ✅reduce(lambda a, b: a if a > b else b, nums)  # ❌max(nums)                                        # ✅

四、itertools 高频实战

itertools 是 Python 标准库中最被低估的模块之一,它提供了一系列高效的迭代器工具。

chain:扁平化多层迭代

将多个可迭代对象串联成一个迭代器:

from itertools import chainbatch1 = [1, 2, 3]batch2 = [4, 5, 6]batch3 = [7, 8, 9]combined = batch1 + batch2 + batch3  # 创建新列表,内存浪费combined = list(chain(batch1, batch2, batch3))  # 惰性,不额外分配内存nested = [[1, 2], [3, 4, 5], [6]]flat = list(chain.from_iterable(nested))  # [1, 2, 3, 4, 5, 6]

groupby:流式分组

groupby 对已排序的可迭代对象进行相邻元素分组:

from itertools import groupbyfrom operator import itemgetterrecords = [    ("2026-01", 100), ("2026-01", 200),    ("2026-02", 150), ("2026-02", 300),    ("2026-03", 250),]records.sort(key=itemgetter(0))for month, group in groupby(records, key=itemgetter(0)):    total = sum(item[1] for item in group)    print(f"{month}: {total}")

islice:切片迭代器

对生成器或无限迭代器做切片,避免转换为列表:

from itertools import islicedef read_large_file(path):    with open(path) as f:        for line in f:            yield line.strip()for line in islice(read_large_file("data.csv"), 100, 200):    process(line)

product:去嵌套循环

多层循环的"降维"利器:

from itertools import productcolors = ["红", "蓝"]sizes = ["S", "M", "L"]materials = ["棉", "涤纶"]results = []for c in colors:    for s in sizes:        for m in materials:            results.append((c, s, m))results = list(product(colors, sizes, materials))

compress:掩码筛选

from itertools import compressdata = ["A", "B", "C", "D", "E"]mask = [True, False, True, False, True]selected = list(compress(data, mask))  # ['A', 'C', 'E']

五、functools.partial:固化参数的工程技巧

partial 固定函数的一部分参数,生成一个新函数,在回调函数和数据处理管线中非常实用:

from functools import partialdef log(level, message, timestamp):    return f"[{level}] {timestamp} - {message}"info_log = partial(log, "INFO")error_log = partial(log, "ERROR")from datetime import datetimenow = datetime.now().isoformat()print(info_log(now, "系统启动"))  # [INFO] 2026-07-14T09:00:00 - 系统启动print(error_log(now, "连接超时"))  # [ERROR] 2026-07-14T09:00:00 - 连接超时

在实际数据处理管线中,partial 常与 map 配合使用:

def process_record(rate, discount, row):    return {        "name": row["name"],        "total": row["price"] * row["qty"] * rate * discount,    }processor = partial(process_record, 1.13, 0.9)  # 税率13%,折扣10%results = list(map(processor, raw_data))

六、实战:构建一条数据清洗管道

综合运用上述工具,构建一条从原始数据到结构化输出的 ETL 管道:

from functools import reduce, partialfrom itertools import chain, isliceimport jsonraw_pages = [    [{"id": 1, "name": " 苹果 ", "price": None, "qty": 3},     {"id": 2, "name": "香蕉", "price": 5.0, "qty": None}],    [{"id": 3, "name": " 橘子 ", "price": 8.0, "qty": 2},     {"id": 4, "name": None, "price": 12.0, "qty": 1}],]all_rows = list(chain.from_iterable(raw_pages))def clean_row(row):    return {        "id": row["id"],        "name": (row["name"] or "").strip(),        "price": row["price"] or 0.0,        "qty": row["qty"] or 0,    }cleaned = list(map(clean_row, all_rows))valid = list(filter(lambda r: r["name"] and r["qty"] > 0, cleaned))def bucket_key(row):    if row["price"] < 5:        return "低价"    elif row["price"] < 10:        return "中价"    return "高价"valid.sort(key=bucket_key)grouped = {}for bucket, items in groupby(valid, key=bucket_key):    count = sum(1 for _ in items)    grouped[bucket] = countprint(json.dumps(grouped, ensure_ascii=False, indent=2))

这条管道全程使用惰性迭代器,即使处理百万级数据也不会一次性加载到内存。

七、总结:什么时候用什么

场景推荐工具原因
简单转换,单可迭代对象
列表推导式
可读性最佳
多可迭代对象并行映射
map
语法简洁,支持多参数
按条件筛选 + 已有函数
filter
语义清晰
累积归约为单个值
reduce
无可替代的折叠能力
扁平化、分组、切片
itertools
惰性、内存友好
固定函数参数
partial
减少重复代码

函数式工具不是列表推导式的替代品,而是你武器库中的互补工具。关键不是用哪种风格,而是选对场景——下次写数据处理代码时,多想想:这个场景用 map + filter + itertools 的组合,会不会比三层 for 循环更好。

最新文章

随机文章