Python
  • 01、基础篇
    • Python基础篇-001. Python简介
    • Python基础篇-002. Hello World
    • Python基础篇-003. 变量类型(一)
    • Python基础篇-004. 常量
    • Python基础篇-005. 运算符
    • Python基础篇-006. 条件语句
    • Python基础篇-007. 循环语句
    • Python基础篇-008. 变量类型(二)
    • Python基础篇-009. 函数(一)
    • Python基础篇-010. 函数(二)
    • Python基础篇-011. 变量作用域
    • Python基础篇-012. 自定义类(一)
    • Python基础篇-013. 自定义类(二)
    • Python基础篇-014. 模块
    • Python基础篇-015. 异常处理
  • 02、进阶篇
    • Python进阶篇-001. 文件IO
    • Python进阶篇-002. main.py
    • Python进阶篇-003. init.py
    • Python进阶篇-004. all
    • Python进阶篇-005. private
    • Python进阶篇-006. lambda表达式
    • Python进阶篇-007. 推导式
    • Python进阶篇-008. 迭代器
    • Python进阶篇-009. 生成器
    • Python进阶篇-010. 多线程
    • Python进阶篇-011. 数据处理基础函数(一)
    • Python进阶篇-012. 数据处理基础函数(二)
    • Python进阶篇-013. 包管理(一)
    • Python进阶篇-014. 包管理(二)
    • Python进阶篇-015. 包管理(三)
    • Python进阶篇-016. 包管理(四)
    • Python进阶篇-017. requirements.txt
    • Python进阶篇-018. venv
    • Python进阶篇-019. 头部注释
    • Python进阶篇-020. 优雅传参
    • Python进阶篇-021. 连接MySQL
  • 03、实践篇
    • Python实践篇-001. GitBook小工具(一)
    • Python实践篇-002. GitBook小工具(二)
Powered by GitBook
On this page
  • 一、创作声明
  • 二、map函数
  • 三、flatMap函数
  • 四、reduceByKey函数
  • 五、解释说明
  • 六、写在最后
  1. 02、进阶篇

Python进阶篇-011. 数据处理基础函数(一)

[toc]

一、创作声明

进阶篇是对基础篇的补充,这里面更多的是各种常用库、高级语法糖的教程,因此,进阶篇的内容会比较零碎。在创作过程中,同样会借助ChatGPT来辅助。

二、map函数

  • 语法:map(func, iterable)

  • 示例:

    # 将列表中的每个元素都加1
    nums = [1, 2, 3, 4, 5]
    result = list(map(lambda x: x + 1, nums))
    print(result)  # 输出:[2, 3, 4, 5, 6]

三、flatMap函数

  • 语法:flatMap(func, iterable)

  • 示例:

    # 将列表中的每个元素拆分成单个字符
    words = ['hello', 'world']
    result = list(flatMap(lambda x: list(x), words))
    print(result)  # 输出:['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

四、reduceByKey函数

  • 语法:reduceByKey(func, iterable)

  • 示例:

    # 统计列表中每个元素的个数
    words = ['apple', 'banana', 'apple', 'orange', 'banana']
    result = reduceByKey(lambda x, y: x + y, words)
    print(result)  # 输出:{'apple': 2, 'banana': 2, 'orange': 1}

五、解释说明

以上示例中,func是一个函数,iterable是一个可迭代对象(如列表、元组等)。map函数将func应用于iterable中的每个元素,并返回一个新的可迭代对象。flatMap函数与map函数类似,但是会将func应用于iterable中的每个元素,并将结果展平为一个新的可迭代对象。reduceByKey函数将func应用于iterable中的每个元素,并按照键进行分组,最后返回一个字典,其中键是iterable中的元素,值是应用func后的结果。

六、写在最后

更多技术分享,点击传送门:https://github.com/maxiaolu66/profile

PreviousPython进阶篇-010. 多线程NextPython进阶篇-012. 数据处理基础函数(二)

Last updated 1 year ago