匿名函数使用:
1.lambda函数的调用方式:
# 匿名函数调用方式1
res = lambda x, y: x + y
print("res的值为:", res(1, 3)) # 输出:res的值为: 4
# 匿名函数调用方式2
res1 = (lambda x, y: x + y)(2, 4)
print("res1的值为:", res1) # res1的值为: 6
2.匿名函数结合列表推导式:
li4 = [i*2 for i in range(10) if i > 5]
print(li4) # 输出:[12, 14, 16, 18]
# 匿名函数结合列表推导式
li3 = [(lambda i: i % 5 == 0)(i) for i in range(6)]
print(li3) # 输出:[True, False, False, False, False, True]
3.三目运算:
# 三目运算
a = 300
b = 200
res = a - b if a > b else print('a<b')
print(res) # 输出:100
a = 100
b = 200
res = a - b if a > b else print('a<b') 输出: a<b
4.lambda函数结合filter,map,zip函数使用
li = [1, 2, 3, 5, 4, 5, 2, 55, 32, 23, 55, 0, -1, -2]
# 过滤掉大于5的数
li2 = filter(lambda x: x <= 5, li)
# filter函数过滤后的数一个迭代器,需要转化为一个可迭代对象一次性展示
print(list(li2)) # 输出:[1, 2, 3, 5, 4, 5, 2, 0, -1, -2]
偏函数的使用:
from functools import partil
from functools import partial
li1 = [1, 2, 3, 11, 22, 33]
li2 = [2, 2, 3, 11, 22, 33]
li3 = [3, 2, 3, 11, 22, 33]
li4 = [4, 2, 3, 11, 22, 33]
li5 = [5, 2, 3, 11, 22, 33]
# 过滤上面个列表中小于6的数保留,调用filter时每次都要传入lambda函数和过滤对象2个参数,麻烦
# res1 = filter(lambda x: x < 6, li1)
# res2 = filter(lambda x: x < 6, li2)
# res3 = filter(lambda x: x < 6, li3)
# res4 = filter(lambda x: x < 6, li4)
# res5 = filter(lambda x: x < 6, li5)
# 偏函数的意义是把固定的传参绑定,后续只需要传变化的1个参数
filter2 = partial(filter, lambda x: x < 6)
print(list(filter2(li1))) # 输出:[1, 2, 3]
print(list(filter2(li2))) # 输出:[2, 2, 3]
print(list(filter2(li3))) # 输出:[3, 2, 3]
print(list(filter2(li4))) # 输出:[4, 2, 3]
print(list(filter2(li5))) # 输出:[5, 2, 3]