Python 常用的十個(gè)高階函數(shù)
一、map():批量加工數(shù)據(jù)
map()函數(shù)對序列中的每個(gè)元素應(yīng)用給定的函數(shù),產(chǎn)生新的迭代器。
平方運(yùn)算
numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # 輸出: [1, 4, 9, 16]
二、filter():篩選符合條件的元素
filter()根據(jù)提供的函數(shù)判斷序列中的元素,只保留函數(shù)返回值為True的元素。
過濾偶數(shù)
numbers = [1, 2, 3, 4, 5]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # 輸出: [2, 4]
三、reduce():累積計(jì)算
reduce()函數(shù)對序列中的元素進(jìn)行累積操作,需要導(dǎo)入functools模塊。
求和
from functools import reduce
numbers = [1, 2, 3, 4]
sum_of_numbers = reduce(lambda x, y: x+y, numbers)
print(sum_of_numbers) # 輸出: 10
四、sorted():排序藝術(shù)
sorted()不僅可以對序列進(jìn)行排序,還能接受一個(gè)比較函數(shù)來自定義排序規(guī)則。
按字符串長度排序
words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words, key=len)
print(sorted_words) # 輸出: ['date', 'apple', 'cherry', 'banana']
五、any()與all():邏輯判斷利器
any()只要序列中有任一元素滿足條件即返回True;all()需所有元素均滿足條件。
檢查列表是否有非零元素
nums = [0, 0, 0, 1]
has_non_zero = any(nums)
print(has_non_zero) # 輸出: True
六、enumerate():索引與元素同行
enumerate()同時(shí)返回元素及其索引,常用于循環(huán)中。
打印索引和元素
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
七、zip():合并迭代器
zip()可以將多個(gè)可迭代對象的元素配對成元組。
合并姓名與年齡
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
people = list(zip(names, ages))
print(people) # 輸出: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
八、reversed():反向遍歷
reversed()返回一個(gè)反轉(zhuǎn)的迭代器。
反向打印列表
numbers = [1, 2, 3, 4, 5]
print(list(reversed(numbers))) # 輸出: [5, 4, 3, 2, 1]
九、list(), dict(), set():構(gòu)造容器
這三個(gè)函數(shù)可將可迭代對象轉(zhuǎn)換為列表、字典或集合。
從元組創(chuàng)建字典
tuples = [(1, 'apple'), (2, 'banana')]
dictionary = dict(tuples)
print(dictionary) # 輸出: {1: 'apple', 2: 'banana'}
十、lambda表達(dá)式:匿名函數(shù)
lambda表達(dá)式用于快速定義簡單函數(shù),常用于高階函數(shù)的參數(shù)。
lambda求和
sum_lambda = lambda x, y: x + y
print(sum_lambda(3, 5)) # 輸出: 8
結(jié)語
高階函數(shù),是Python中的一把鋒利的寶劍,它們不僅簡化了代碼,還提高了代碼的可讀性和可維護(hù)性。掌握這些函數(shù),就如同獲得了解鎖編程難題的魔法鑰匙,讓代碼世界在你手中綻放出無限可能。繼續(xù)探索,你會(huì)發(fā)現(xiàn)Python的每一個(gè)角落都藏著驚喜。???
以上就是本次關(guān)于Python高階函數(shù)的分享,希望這些示例能激發(fā)你對函數(shù)式編程的興趣,讓你的編程之旅更加精彩!