python的lambda函数的常用场景,Python如何使用Lambda函数?

本文概述

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

匿名函数包含一小段代码。它模拟C和C ++的内联函数, 但不完全是内联函数。

下面给出了定义匿名函数的语法。

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

为什么要使用lambda函数?

当我们在另一个函数中匿名使用lambda函数的主要角色时, 可以在场景中更好地描述它们。在python中, lambda函数可用作自变量, 而高阶函数可用作自变量。在需要考虑以下示例的情况下, 也可以使用Lambda函数。

例子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

将lambda函数与过滤器一起使用

#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

在地图上使用lambda函数

#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]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值