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)
相关推荐
松仔log10 小时前
Kotlin中级——KMP
android·开发语言·kotlin
龙腾AI白云10 小时前
多源数据融合:把零散信号拼成一致图景
大数据·人工智能·python·机器学习·知识图谱
H H.10 小时前
Java笔记:String字符串
java·开发语言·经验分享·笔记·其他
艾派森10 小时前
深度学习实战-基于VGG19的健康和白化珊瑚图像分类识别模型
人工智能·python·深度学习·分类
鲸渔10 小时前
【AI Agent系列课程26-Python 基础26】复盘:Python 接口开发知识清单
开发语言·python·ai编程
sharemylove11 小时前
Java 异常处理 学习笔记
java·开发语言·经验分享·笔记·学习
西西弗Sisyphus11 小时前
Qt QML 程序是怎么跑起来的(1)qml-only
开发语言·c++·qt
2401_8685347811 小时前
55 个热门网络面试问题及答案
网络·python
aifannihao11 小时前
ON CONFLICT 冲突后返回空:sqlite3 实测 get-or-create
数据库·python·postgresql·sqlite3·标准库
用户03321266636711 小时前
使用 Python 合并 Excel 工作簿
python