python中的filter、map、reduce、apply用法总结

Python序列操作详解
本文深入讲解Python中的filter、map、reduce及pandas的apply函数,详细介绍各函数的用途、调用方式与实例,帮助读者掌握Python序列处理技巧。
OUTLINE

    filter
    map
    reduce
    apply
    总结

filter

功能: filter的功能是过滤掉序列中不符合函数条件的元素,当序列中要删减的元素可以用某些函数描述时,就应该想起filter函数。
调用: filter(function,sequence),function可以是匿名函数或者自定义函数,它会对后面的sequence序列的每个元素判定是否符合函数条件,返回TRUE或者FALSE,从而只留下TRUE的元素;sequence可以是列表、元组或者字符串
例子:

x = [1,2,3,4,5]
list(filter(lambda x:x%2==0,x)) # 找出偶数。python3.*之后filter函数返回的不再是列表而是迭代器,所以需要用list转换。
# 输出:
[2, 4]

    1
    2
    3
    4

map

功能: 求一个序列或者多个序列进行函数映射之后的值,就该想到map这个函数,它是python自带的函数,在python3.*之后返回的是迭代器,同filter,需要进行列表转换
调用: map(function,iterable1,iterable2),function中的参数值不一定是一个x,也可以是x和y,甚至多个;后面的iterable表示需要参与function运算中的参数值,有几个参数值就传入几个iterable
例子:

x = [1,2,3,4,5]
y = [2,3,4,5,6]
list(map(lambda x,y:(x*y)+2,x,y))
# 输出:
[4, 8, 14, 22, 32]

    1
    2
    3
    4
    5

注:map中如果传入的几个序列的长度不一,那么会依据最短的序列进行计算。
reduce

功能: 对一个序列进行压缩运算,得到一个值。但是reduce在python2的时候是内置函数,到了python3移到了functools模块,所以使用之前需要 from functools import reduce
调用: reduce(function,iterable),其中function必须传入两个参数,iterable可以是列表或者元组
例子:

from functools import reduce
y = [2,3,4,5,6]
reduce(lambda x,y: x + y,y) # 直接返回一个值

    1
    2
    3

其计算原理:
先计算头两个元素:f(2, 3),结果为5;
再把结果和第3个元素计算:f(5, 4),结果为9;
再把结果和第4个元素计算:f(9, 5),结果为14;
再把结果和第5个元素计算:f(14, 6),结果为20;
由于没有更多的元素了,计算结束,返回结果20。
apply

功能: 是pandas中的函数,应用对象为pandas中的DataFrame或者Series。大致有两个方面的功能:一是直接对DataFrame或者Series应用函数,二是对pandas中的groupby之后的聚合对象apply函数
调用: apply(function,axis),function表明所使用的函数,axis表明对行或者列做运算
例子:

import numpy as np
a = np.random.randint(low=0,high=4,size=(2,4))
data = pd.DataFrame(a)
data.apply(lambda x:x*10)
# 输出:

    1
    2
    3
    4
    5

总结

1、filter和map都是python内置的函数,可以直接调用,reduce在functools模块,apply在pandas模块
2、要过滤删减序列用filter;要对多个序列做函数运算用map;在pandas里面直接调用apply,尤其是聚合对象,当然还有agg,日后补充。reduce用得少。
--------------------- 
作者:Emily_2018 
来源:优快云 
原文:https://blog.youkuaiyun.com/qq_32618817/article/details/80633848 
版权声明:本文为博主原创文章,转载请附上博文链接!

 

Python中,虽然内置了`map()`、`filter()`和`reduce()`等高阶函数,但我们完全可以用闭包函数来模拟它们的功能。闭包是一个可以访问其自身词法环境中的变量的函数,这就使得我们可以创建一些“记住”状态的函数。 以下是模拟这三个函数的例子: 1. **模拟map()**: ```python def map_func(func, iterable): result = [] def inner(item): result.append(func(item)) for item in iterable: inner(item) return result # 使用示例 square = lambda x: x * x numbers = [1, 2, 3, 4] squared_numbers = map_func(square, numbers) # 输出:[1, 4, 9, 16] ``` 2. **模拟filter()**: ```python def filter_func(predicate, iterable): result = [] def inner(item): if predicate(item): result.append(item) for item in iterable: inner(item) return result # 使用示例 is_even = lambda x: x % 2 == 0 even_numbers = filter_func(is_even, numbers) # 输出:[2, 4] ``` 3. **模拟reduce()** (注意Python 3中不再直接提供reduce函数,但可以使用functools库的reduce()或lambda表达式代替): ```python from functools import reduce def reduce_func(func, iterable, initial=None): def inner(acc, item): return func(acc, item) return reduce(inner, iterable, initial) # 示例 factorial = lambda acc, n: acc * n if n > 0 else acc number_product = reduce_func(factorial, numbers, 1) # 输出:24 ``` **将它们封装为一个通用的高阶函数**: ```python def apply_operator(op_func, iterable, operation='map', initial=None): if operation == 'map': return op_func(iterable) elif operation == 'filter': return op_func(lambda pred, it: iterable if pred(it) else [], iterable) elif operation == 'reduce': return op_func(reduce_func, iterable, initial) else: raise ValueError(f"Unsupported operation: {operation}") # 调用方式不变 apply_map = lambda func, iterable: apply_operator(op_func=func, iterable=iterable, operation='map') apply_filter = lambda predicate, iterable: apply_operator(op_func=lambda pred, it: pred(it), iterable=iterable, operation='filter') apply_reduce = lambda func, iterable, initial=None: apply_operator(op_func=func, iterable=iterable, operation='reduce') ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值