目录
- 介绍
- 小编环境
- 生成不同的聚合函数
介绍
偏函数(functools.partial),主要用来解决函数中某些参数是已知的固定值。利用偏函数的概念,可以生成一些新的函数,在调用这些新函数时,不用再传递固定值的参数,这样可以使代码更简洁
下面列举一些偏函数的巧妙使用方法,在使用偏函数时,需要从标准库functools中导入
from functools import partial
小编环境
import sys
print(\’python 版本:\’,sys.version.split(\’|\’)[0])
#python 版本: 3.11.4
生成不同的聚合函数
1. 创建底层的元函数、函数类
from functools import partial
def aggregation_fn_meta(aggregation_fn, values):
return aggregation_fn(values)
def aggregation_fn_class(aggregation_fn):
return partial(aggregation_fn_meta, aggregation_fn)
2. 基于函数类,来生成不同的聚合函数
基于内建函数创建(python中可以直接使用的函数)
sum_fn=aggregation_fn_class(sum)
sum_fn([1,2,3,4,5,1,2,10]) #28
max_fn=aggregation_fn_class(max)
max_fn([1,2,3,4,5,1,2,10]) #10
min_fn=aggregation_fn_class(min)
min_fn([1,2,3,4,5,1,2,10])
基于自定义函数创建
def count(values):
return len(values)
count_fn=aggregation_fn_class(count)
count_fn([1,2,3,4,5,1,2,10]) #8
def distinct_count(values):
return len(set(values))
distinct_count_fn=aggregation_fn_class(distinct_count)
distinct_count_fn([1,2,3,4,5,1,2,10]) #6
到此这篇关于Python利用partial偏函数生成不同的聚合函数的文章就介绍到这了,更多相关Python生成不同的聚合函数内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!
您可能感兴趣的文章:
- Python Pandas聚合函数的应用示例
- Python自定义聚合函数merge与transform区别详解
- Python DataFrame.groupby()聚合函数,分组级运算