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

Last updated