Lambda表達式是一種在PythonA quick way to create anonymous functions in .An anonymous function is like a one-time-use function,沒有名字.You only need to use it once,Then move on in the program.Lambda 函數通常與 map() 和[filter()]結合使用.lambdaMethods of functions are a convenient way to quickly define a function that can be used with these functions in a shorthand form.在本教程中,We will introduce a few examples,說明如何在 Python 中定義 lambda 函數,and how to use them effectively.
一個LambdaFunctions are just plainPythonA shorthand version of the function.So to better understand how inPython中制作一個lambda函數,We can turn an ordinary function into one step by steplambda函數.首先,Let's look at a standard Python 函數的簡單例子.
def plus_one(num):
result = num + 1
return result
復制代碼
plus_one(7)
復制代碼
8
復制代碼
result
變量We can simply return the result of this calculation,而不是取num變量,加一,Then store in the result.
def plus_one(num):
return num + 1
復制代碼
plus_one(7)
復制代碼
8
復制代碼
Now we can simplify the function even further by doing the calculation in one line.
def plus_one(num): return num + 1
復制代碼
plus_one(7)
復制代碼
8
復制代碼
def
關鍵字在這裡,我們把defKeyword and the function we assign to us**(def plus_one()**)is removed along with the parentheses.
num: return num + 1
復制代碼
return
關鍵字Lambda functions do not返回語句,Because any lambda function would imply返回語句.
num: num + 1
復制代碼
lambda
關鍵詞最後,We can prepend the stripped expressionlambda關鍵字,瞧!這就是一個lambda函數.我們就有了一個lambda函數.
lambda num: num + 1
復制代碼
為了利用lambda函數,You will often combine it with other functions egmap()或filter()結合起來使用.It is also commonly associated with reduce()函數一起使用.We'll look at this later.然而,你使用lambdaThe first way is to simply assign it to a variable,Then use that variable as a function.Let's see how this is done.
plus_one = lambda num: num + 1
復制代碼
plus_one(7)
復制代碼
8
復制代碼
lambda
函數與 map()
map()The first argument to a function is always a function itself.它被稱為轉換函數.下面是一個使用map()的lambda的例子.
nums = [1, 2, 3, 4, 5]
result = map(lambda x: x * 2, nums)
print(list(result))
復制代碼
[2, 4, 6, 8, 10]
復制代碼
lambda
函數與 filter()
filter()The function creates a list of elements for which the function returns true.它經常與lambda表達式一起使用.這裡有一個例子,We just want greater than3的數字.
nums = [1, 2, 3, 4, 5]
result = filter(lambda x: x > 3, nums)
print(list(result))
復制代碼
[4, 5]
復制代碼
lambda
函數與 reduce()
reduce()The function performs rolling calculations on consecutive pairs of values in a list.A common example is summing all values in a list,So let's try it on our simple list of numbers.
from functools import reduce
nums = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, nums)
print(result)
復制代碼
15
復制代碼
if
語句與lambda你能用 lambda 函數使用 Python 的if語句嗎?Why yes,你可以.讓我們看一個例子.
result = map(lambda str: str.capitalize() if 'a' in str else str, 'abracadabra')
print(list(result))
復制代碼
['A', 'b', 'r', 'A', 'c', 'A', 'd', 'A', 'b', 'r', 'A']
復制代碼
def
.