# Python如何使用Lambda函数？

## 本文概述

Python允许我们不以标准方式声明函数, 即使用def关键字。而是使用lambda关键字声明匿名函数。但是, Lambda函数可以接受任意数量的参数, 但是它们只能以表达式形式返回一个值。

``lambda arguments : expression``

## 例子1

``````x = lambda a:a+10 # a is an argument and a+10 is an expression which got evaluated and returned.
print("sum = ", x(20))``````

``sum =  30``

## 例子2

Lambda函数的多个参数

``````x = lambda a, b:a+b # a and b are the arguments and a+b is the expression which gets evaluated and returned.
print("sum = ", x(20, 10))``````

``sum =  30``

## 例子1

``````#the function table(n) prints the table of n
def table(n):
return lambda a:a*n; # a will contain the iteration variable i and a multiple of n is returned at each function call
n = int(input("Enter the number?"))
b = table(n) #the entered number is passed into the function table. b will contain a lambda function which is called again and again with the iteration variable i
for i in range(1, 11):
print(n, "X", i, "=", b(i)); #the lambda function b is called with the iteration variable i, ``````

``````Enter the number?10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100``````

## 例子2

``````#program to filter out the list which contains odd numbers
List = {1, 2, 3, 4, 10, 123, 22}
Oddlist = list(filter(lambda x:(x%3 == 0), List)) # the list contains all the items of the list for which the lambda function evaluates to true
print(Oddlist)``````

``[3, 123]``

## 例子3

``````#program to triple each number of the list using map
List = {1, 2, 3, 4, 10, 123, 22}
new_list = list(map(lambda x:x*3, List)) # this will return the triple of each item of the list and add it to new_list
print(new_list)``````

``[3, 6, 9, 12, 30, 66, 369]``

• 回顶