Python中的lambda函數是什麼,為什麼我們需要它?

WBOY
發布: 2023-08-25 14:41:13
轉載
1190 人瀏覽過

Python中的lambda函數是什麼,為什麼我們需要它?

在本文中,我們將學習 Python 中的 lambda 函數以及為什麼需要它,並查看 lambda 函數的一些實際範例。

Python 中的 lambda 函數是什麼?

Lambda 函數通常稱為“匿名函數”, 與普通 Python 函數相同,只不過它可以不帶名稱進行定義。 >def關鍵字用於定義普通函數,而lambda關鍵字用於定義匿名函數。然而,它們僅限於單行表達。它們與常規函數一樣,可以接受多個參數。

文法

lambda arguments: expression
登入後複製
  • 此函數接受任意數量的輸入,但僅計算並傳回一個表達式。

  • Lambda 函數可以用在任何需要函數物件的地方。

  • 您必須記住,lambda 函數在語法上僅限於單一表達式。

  • 除了函數中的其他類型的表達式之外,它在特定的程式設計領域還有多種用途。

為什麼我們需要 Lambda 函數?

  • 與使用 def 關鍵字編寫的普通 Python 函數相比,lambda 函數需要更少的程式碼行。然而,這並不完全正確,因為使用 def 定義的函數可以在一行中定義。但是,def 函數通常定義在不只一行上。

  • 它們通常在需要較短時間(臨時)的函數時使用,通常在另一個函數(例如過濾器、映射或歸約)中使用。

  • 您可以定義一個函數並在定義結束時使用 lambda 函數立即呼叫它。這對於 def 函數來說是不可能的。

Python Lambda 函數的簡單範例

範例

# input string 
inputString = 'TUTORIALSpoint'
 
# converting the given input string to lowercase and reversing it
# with the lambda function
reverse_lower = lambda inputString: inputString.lower()[::-1]

print(reverse_lower(inputString))
登入後複製

輸出

執行時,上述程式將產生以下輸出 -

tniopslairotut
登入後複製

在條件檢查中使用 Lambda 函數

範例

# Formatting number to 2 decimal places using lambda function
formatNum = lambda n: f"{n:e}" if isinstance(n, int) else f"{n:,.2f}"
 
print("Int formatting:", formatNum(1000))
print("float formatting:", formatNum(5555.4895412))
登入後複製

輸出

執行時,上述程式將產生以下輸出 -

Int formatting: 1.000000e+03
float formatting: 5,555.49
登入後複製

Lambda 函數和 def 定義函數有什麼不同?

範例

# creating a function that returns the square root of 
# the number passed to it
def square(x):
	return x*x


# using lambda function that returns the square root of 
# the number passed 
lambda_square = lambda x: x*x


# printing the square root of the number by passing the
# random number to the above-defined square function with the def keyword
print("Square of the number using the function with 'def' keyword:", square(4))

# printing the square root of the number by passing the
# random number to the above lambda_square function with lambda keyword
print("Square of the number using the function with 'lambda' keyword:", lambda_square(4))
登入後複製

輸出

執行時,上述程式將產生以下輸出 -

Square of the number using the function with 'def' keyword: 16
Square of the number using the function with 'lambda' keyword: 16
登入後複製

如前面的範例所示,square()lambda_square () 函數的工作方式相同且符合預期。讓我們仔細看看這個例子,找出它們之間的差異 -

使用 lambda 函數 不使用 lambda 函數
支援傳回某個值的單行語句。 允許功能塊內有任意數量的行。
非常適合進行小型操作或資料操作。 這在需要多行程式碼的情況下非常有用。
降低程式碼可讀性 我們可以透過使用註解和功能解釋來提高可讀性。

Python lambda 函數實際用途

範例

將 Lambda 函數與列表理解結合使用

is_odd_list = [lambda arg=y: arg * 5 for y in range(1, 10)]
 
# looping on each lambda function and calling the function
# for getting the multiplied value
for i in is_odd_list:
	print(i())
登入後複製

輸出

執行時,上述程式將產生以下輸出 -

5
10
15
20
25
30
35
40
45
登入後複製

在列表推導式的每次迭代中,都會建立一個具有預設參數 y 的新 lambda 函數(其中 y 是迭代中的目前項目)。隨後,在 for 迴圈中,我們使用 i() 使用預設參數呼叫相同的函數物件並取得所需的值。因此,is_odd_list 保存 lambda 函數物件清單。

範例

將 Lambda 函數與 if-else 條件語句結合使用

# using lambda function to find the maximum number among both the numbers
find_maximum = lambda x, y : x if(x > y) else y
 
print(find_maximum(6, 3))
登入後複製

輸出

執行時,上述程式將產生以下輸出 -

6
登入後複製

範例

將 Lambda 函數與多個語句結合使用

inputList = [[5,2,8],[2, 9, 12],[10, 4, 2, 7]]

# sorting the given each sublist using lambda function
sorted_list = lambda k: (sorted(e) for e in k)

# getting the second-largest element 
second_largest = lambda k, p : [x[len(x)-2] for x in p(k)]
output = second_largest(inputList, sorted_list)

# printing the second largest element
print(output)
登入後複製

輸出

執行時,上述程式將產生以下輸出 -

[5, 9, 7]
登入後複製

帶有filter()的Python lambda函數

範例

inputList = [3, 5, 10, 7, 24, 6, 1, 12, 8, 4]

# getting the even numbers from the input list 
# using lambda and filter functions
evenList = list(filter(lambda n: (n % 2 == 0), inputList))
# priting the even numbers from the input list
print("Even numbers from the input list:", evenList)
登入後複製

輸出

執行時,上述程式將產生以下輸出 -

Even numbers from the input list: [10, 24, 6, 12, 8, 4]
登入後複製

帶有map()的Python lambda函數

Python 的 map() 函數接受一個函數和一個列表作為參數。使用 lambda 函數和列表呼叫該函數,它會傳回一個新列表,其中包含該函數為每個項目返回的所有 lambda 更改的項目。

範例

使用 lambda 和 map() 函數將所有列表元素轉換為小寫

# input list
inputList = ['HELLO', 'TUTORIALSpoint', 'PyTHoN', 'codeS']

# converting all the input list elements to lowercase using lower()
# with the lambda() and map() functions and returning the result list
lowercaseList = list(map(lambda animal: animal.lower(), inputList))

# printing the resultant list
print("Converting all the input list elements to lowercase:\n", lowercaseList)
登入後複製

輸出

執行時,上述程式將產生以下輸出 -

Converting all the input list elements to lowercase:
 ['hello', 'tutorialspoint', 'python', 'codes']
登入後複製

結論

在本教程中,我們透過大量範例深入學習了 Python 中的 lambda 函數。我們也了解了 lambda 函數和 def 函數之間的差異。

以上是Python中的lambda函數是什麼,為什麼我們需要它?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!