Python中的Lambda匿名函數

背景

Lambda匿名函數在Python中經常出現,小巧切靈活,使用起來特別方便,但是小編建議大家少使用,最好多寫幾行代碼,自定義個函數。

既然Python中存在Lambda匿名函數,那么小編本著存在即合理的原則,還是介紹一下,本篇文章翻譯自《Lambda Functions in Python》,分享出來供大家參考學習

原文地址:https://www.clcoding.com/2024/03/lambda-functions-in-python.html

案例1:基本語法

常規函數

def add(x, y):
    return x + y

匿名函數

lambda_add = lambda x, y: x + y

調用2種類型函數

print(add(3, 5))   #8
print(lambda_add(3, 5))    #8

案例2:在sorted排序函數中使用匿名函數

students = [("Alice", 25), ("Bob", 30), ("Charlie", 22)]

sorted_students = sorted(students, key=lambda student: student[1])

print("Sorted Students by Age:", sorted_students)
#Sorted Students by Age: [('Charlie', 22), ('Alice', 25), ('Bob', 30)]

案例3:在filter過濾函數中使用匿名函數

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print("Even Numbers:", even_numbers)
#Even Numbers: [2, 4, 6, 8]

案例4:在map函數中使用匿名函數

numbers = [1, 2, 3, 4, 5]

squared_numbers = list(map(lambda x: x**2, numbers))

print("Squared Numbers:", squared_numbers)
#Squared Numbers: [1, 4, 9, 16, 25]

案例5:在max函數中使用匿名函數

numbers = [10, 5, 8, 20, 15]

max_number = max(numbers, key=lambda x: -x)

print("Maximum Number:", max_number)
#Maximum Number: 5

案例6:在sorted排序函數中,多個排序條件

people = [{"name": "Charlie", "age": 25}, 
          {"name": "Bob", "age": 30}, 
          {"name": "Alice", "age": 25}]

sorted_people = sorted(people, 
                       key=lambda person: (person["age"], person["name"]))

print("Sorted People:", sorted_people)
#Sorted People: [{'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 25}, {'name': 'Bob', 'age': 30}]

案例7:在reduce函數中使用匿名函數

from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print("Product of Numbers:", product)
#Product of Numbers: 120

案例8:在條件表達式中使用匿名函數

numbers = [10, 5, 8, 20, 15]

filtered_and_squared = list(map(lambda x: x**2 if x % 2 == 0 else x, numbers))

print("Filtered and Squared Numbers:", filtered_and_squared)
#Filtered and Squared Numbers: [100, 5, 64, 400, 15]

歷史相關文章


以上是自己實踐中遇到的一些問題,分享出來供大家參考學習,歡迎關注微信公眾號:DataShare ,不定期分享干貨

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容