Anonymous function of lambda function in python

The basic syntax format is as follows:

lambda arg1,arg2,arg3....argn:expression 

The parameter and the result are separated by a colon, the parameter (arg) is before the colon, and the specific expression (expression) is after the colon. According to the actual situation, there can be multiple parameters of the colon money.

Concrete operation

lambda1 = lambda x,y : x+y
res1 = lambda1(3,6)
print(res1)   #打印结果为:9

lambda2 = lambda x,y : x-y
res2 = lambda2(3,6)
print(res2)   #打印结果为:-3

lambda3 = lambda x,y : x*y
res3 = lambda3(3,6)
print(res3)     #打印结果为:18

lambda4 = lambda x,y : x/y
res4 = lambda4(3,6)
print(res4)    #打印结果为:0.5

define anonymous function

def add(a,b=1):
    return a + b
print(add(10,20))	  	#返回结果为:30
print(add(10))			#打印结果为:11

#上面的代码等同于下面的这行代码,
add_lambda = lambda a,b=1:a+b
print(add_lambda(10,20))    #返回结果为:30
print(add_lambda(10))    	#打印结果为:11

Use the if condition to judge:

get_add = lambda x:'even' if x % 2 == 0 else 'odd'
#  even:偶数(伊问) odd:奇数(额德)

print('8 is',get_add(8))    #打印结果为:8 is even
print('9 is',get_add(9))    #打印结果为:9 is odd

No parameter expression:

import random
# random.random():表示生成0-1之间的随机数
ran_lambda = lambda :random.random()

# 注意打印的时候需要加括号
print(ran_lambda())   #打印结果为:0.16933409403919808

The relationship of map:

def add(x):   #定义一个类
    return x**2
#注意,后面给的值是不能使用int类型 数据
mobj = map(add,[1,2,3,4])  #列表中是数据,就是一次传给add这个函数的参数值
print(mobj)			#打印结果为:<map object at 0x000001819ABC70B8>
print(list(mobj))   #打印结果为:[1, 4, 9, 16]

mobj = map(add,(1,2,3,4))
print(mobj)			#打印结果为:<map object at 0x000001819AC71DD8>
print(tuple(mobj))  #打印结果为:(1, 4, 9, 16)


#上面的代码转换成lambda的匿名函数:
mobj1 = map(lambda x:x**2,[1,2,3,4])
print(list(mobj1))      #打印结果为:[1, 4, 9, 16]

mobj1 = map(lambda x:x**2,(1,2,3,4))
print(tuple(mobj1))     #打印结果为:(1, 4, 9, 16)

Guess you like

Origin blog.csdn.net/m0_57028677/article/details/128007137