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