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


在本文中,我們將學習Python中的lambda函式,為什麼我們需要它,並檢視lambda函式的一些實際示例。

什麼是Python中的lambda函式?

Lambda函式,通常稱為“匿名函式”,與普通的Python函式相同,只是它可以無需名稱進行定義。普通的函式使用def關鍵字定義,而匿名函式使用lambda關鍵字定義。但是,它們僅限於單行表示式。與普通函式一樣,它們可以接受多個引數。

語法

lambda arguments: expression
  • 此函式可以接受任意數量的輸入,但只計算並返回一個表示式。

  • Lambda函式可以在需要函式物件的地方使用。

  • 必須記住,lambda函式在語法上僅限於單行表示式。

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

為什麼我們需要Lambda函式?

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

  • 它們通常在需要較短時間(臨時)的函式時使用,通常用於另一個函式內部,例如filter、map或reduce。

  • 您可以使用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]

Python lambda函式與filter()

示例

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]

Python lambda函式與map()

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函式之間的區別。

更新於:2022年12月15日

2000+ 次瀏覽

開啟您的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.