Python利用partial偏函數(shù)生成不同的聚合函數(shù)
介紹
偏函數(shù)(functools.partial),主要用來解決函數(shù)中某些參數(shù)是已知的固定值。利用偏函數(shù)的概念,可以生成一些新的函數(shù),在調(diào)用這些新函數(shù)時,不用再傳遞固定值的參數(shù),這樣可以使代碼更簡潔
下面列舉一些偏函數(shù)的巧妙使用方法,在使用偏函數(shù)時,需要從標準庫functools中導入
from functools import partial
小編環(huán)境
import sys
print('python 版本:',sys.version.split('|')[0])
#python 版本: 3.11.4
生成不同的聚合函數(shù)
1. 創(chuàng)建底層的元函數(shù)、函數(shù)類
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. 基于函數(shù)類,來生成不同的聚合函數(shù)
基于內(nèi)建函數(shù)創(chuàng)建(python中可以直接使用的函數(shù))
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])
基于自定義函數(shù)創(chuàng)建
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到此這篇關(guān)于Python利用partial偏函數(shù)生成不同的聚合函數(shù)的文章就介紹到這了,更多相關(guān)Python生成不同的聚合函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python基于微信OCR引擎實現(xiàn)高效圖片文字識別
這篇文章主要為大家詳細介紹了一款基于微信OCR引擎的圖片文字識別桌面應(yīng)用開發(fā)全過程,可以實現(xiàn)從圖片拖拽識別到文字提取,感興趣的小伙伴可以跟隨小編一起學習一下2025-06-06
12個Python程序員面試必備問題與答案(小結(jié))
這篇文章主要介紹了12個Python程序員面試必備問題與答案,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-06-06

