python中的高階函數(shù)示例詳解
1.定義
高階函數(shù)(Higher-order Function)是指能夠接受其他函數(shù)作為參數(shù),或者將函數(shù)作為返回值的函數(shù)。在Python中,函數(shù)是一等公民(First-class Citizen),這意味著函數(shù)可以像其他數(shù)據(jù)類型一樣被傳遞和使用。
高階函數(shù)有以下三個(gè)特征:
函數(shù)可以作為參數(shù)傳遞
函數(shù)可以作為返回值
函數(shù)可以賦值給變量
2.map函數(shù)
map(function, iterable) 將函數(shù)應(yīng)用于可迭代對(duì)象的每個(gè)元素,返回一個(gè)迭代器。
其中l(wèi)ambda是匿名函數(shù)。在此處代表一個(gè)任意函數(shù)。
# 將列表中的每個(gè)元素平方
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# 使用普通函數(shù)
def square(x):
return x**2
squared = list(map(square, numbers))3.filter函數(shù)
filter(function, iterable) 根據(jù)函數(shù)的返回值(True/False)來過濾元素。
# 過濾出偶數(shù) numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # [2, 4, 6, 8, 10] # 過濾出長(zhǎng)度大于3的字符串 words = ["apple", "cat", "dog", "elephant"] long_words = list(filter(lambda word: len(word) > 3, words)) print(long_words) # ["apple", "elephant"]
4.reduce函數(shù)
reduce(function, iterable[, initializer]) 對(duì)可迭代對(duì)象中的元素進(jìn)行累積計(jì)算(需要從functools導(dǎo)入)。
from functools import reduce # 計(jì)算乘積 numbers = [1, 2, 3, 4, 5] product = reduce(lambda x, y: x * y, numbers) print(product) # 120 # 找出最大值 max_value = reduce(lambda x, y: x if x > y else y, numbers) print(max_value) # 5
5.sorted函數(shù)
sorted(iterable, key=None, reverse=False) 根據(jù)key函數(shù)對(duì)可迭代對(duì)象進(jìn)行排序。
# 按字符串長(zhǎng)度排序 words = ["apple", "cat", "dog", "banana"] sorted_words = sorted(words, key=len) print(sorted_words) # ['cat', 'dog', 'apple', 'banana'] # 按第二個(gè)字符排序 sorted_by_second = sorted(words, key=lambda x: x[1]) print(sorted_by_second) # ['banana', 'cat', 'apple', 'dog']
6.自定義高階函數(shù)
# 函數(shù)作為參數(shù)
def apply_twice(func, value):
"""將函數(shù)應(yīng)用兩次"""
return func(func(value))
result = apply_twice(lambda x: x * 2, 3)
print(result) # 12 (3*2=6, 6*2=12)
# 函數(shù)作為返回值
def create_multiplier(factor):
"""創(chuàng)建一個(gè)乘法器函數(shù)"""
def multiplier(x):
return x * factor
return multiplier
double = create_multiplier(2)
triple = create_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15上述代碼分別是函數(shù)作為參數(shù)和函數(shù)作為返回值的兩種情況。
現(xiàn)在掌握了如何自定義高階函數(shù)后,結(jié)合裝飾器@使用以下:
def timer_decorator(func):
"""計(jì)算函數(shù)執(zhí)行時(shí)間的裝飾器"""
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} 執(zhí)行時(shí)間: {end - start:.4f}秒")
return result
return wrapper
@timer_decorator
def slow_function():
import time
time.sleep(1)
return "完成"
result = slow_function() # 會(huì)自動(dòng)打印執(zhí)行時(shí)間最后,高階函數(shù)是Python函數(shù)式編程的重要組成部分,熟練掌握它們可以寫出更加優(yōu)雅和高效的代碼。
總結(jié)
到此這篇關(guān)于python中高階函數(shù)的文章就介紹到這了,更多相關(guān)python高階函數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pandas實(shí)現(xiàn)一列數(shù)據(jù)分隔為兩列
這篇文章主要介紹了Pandas實(shí)現(xiàn)一列數(shù)據(jù)分隔為兩列,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05
解決python -m pip install --upgrade pip 升級(jí)不成功問題
這篇文章主要介紹了python -m pip install --upgrade pip 解決升級(jí)不成功問題,需要的朋友可以參考下2020-03-03
python實(shí)現(xiàn)簡(jiǎn)單井字棋小游戲
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)簡(jiǎn)單井字棋小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03
Python腳本操作Excel實(shí)現(xiàn)批量替換功能
這篇文章主要介紹了Python腳本操作Excel實(shí)現(xiàn)批量替換功能,本文使用的是Openpyxl工具,通過實(shí)例截圖給大家講解的非常詳細(xì),需要的朋友可以參考下2019-11-11
python運(yùn)用requests模擬瀏覽器發(fā)送請(qǐng)求過程
模擬瀏覽器請(qǐng)求可選用requests處理靜態(tài)內(nèi)容,selenium應(yīng)對(duì)動(dòng)態(tài)頁面,playwright支持高級(jí)自動(dòng)化,設(shè)置代理和超時(shí)參數(shù),根據(jù)需求選擇合適工具2025-07-07
python Airtest自動(dòng)化測(cè)試工具的的使用
本文主要介紹了python Airtest自動(dòng)化測(cè)試工具的的使用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02

