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