Python中重要的内建高阶函数

Python中重要的内建高阶函数

在Python中,filter、sorted、map 和 reduce 是一些内建的高阶函数,用于对可迭代对象进行过滤、排序、映射和累积操作。

filter 函数

  • 语法:filter(function, iterable)

  • 作用:用于过滤可迭代对象中的元素,返回一个由使得 function 返回 True 的元素所组成的迭代器。

  • 示例:

    py 复制代码
    # 过滤出偶数
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    result = filter(lambda x: x % 2 == 0, numbers)
    print(list(result))  # 输出 [2, 4, 6, 8, 10]
    py 复制代码
    >>> def f(x) :
    	return True if x % 2 == 0 else False
    
    >>> number = [i for i in range(1, 10)]
    >>> list(filter(f, number))
    [2, 4, 6, 8]

sorted 函数

  • 语法:sorted(iterable, key=key, reverse=reverse)

  • 作用:对可迭代对象进行排序,返回一个新的已排序列表。

  • 示例:

    py 复制代码
    # 对字符串列表按长度排序
    words = ['apple', 'banana', 'kiwi', 'orange']
    result = sorted(words, key=len)
    print(result)  # 输出 ['kiwi', 'apple', 'banana', 'orange']

map 函数

  • 语法:map(function, iterable, ...)

  • 作用:对可迭代对象的每个元素应用一个函数,返回一个由应用函数后的结果组成的迭代器。

  • 示例:

    py 复制代码
    # 对列表中的每个元素求平方
    numbers = [1, 2, 3, 4, 5]
    result = map(lambda x: x**2, numbers)
    print(list(result))  # 输出 [1, 4, 9, 16, 25]

reduce 函数

  • 需要导入:from functools import reduce

  • 语法:reduce(function, iterable[, initializer])

  • 作用:对可迭代对象中的元素进行累积操作,返回一个单一的累积结果。

  • 示例:

    py 复制代码
    from functools import reduce
    
    # 计算列表中所有元素的乘积
    numbers = [2, 3, 4, 5]
    result = reduce(lambda x, y: x * y, numbers)
    print(result)  # 输出 120 (2 * 3 * 4 * 5)
相关推荐
曲幽10 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户83562907805114 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞17 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派19 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪21 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户03321266636721 小时前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫1 天前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派1 天前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风1 天前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽1 天前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic