文章内容:
1.lambda表达式在python中的体现
2.如何调用匿名函数
3.三元表达式
4.如何将for循环用map代替写出来
5.利用reduce连续调用lambda
6.filter过滤,数据清洗
def add(x,y):
return x+y
"""
lambda表达式
匿名函数
用匿名函数代替上面函数表示
lambda parameter_list:expression
"""
f=lambda x,y:x+y#冒号后面只能是表达式,非常适合使用三元表达式去写if/else逻辑
"""
调用函数
"""
print(add(4,5))#9
"""
如何调用匿名函数
"""
print(f(5,6))#11
"""
三元表达式
x>y?x:y
"""
x=4
y=5
r=x if x>y else y
print(r)#5
####################################################################
"""
map
映射
简单地来说就是一个映射
"""
list_x=[1,2,3,4,5,6,7,8,9]
def f1(x):
return x*x
"""
for x in list_x:
f1(x)
可以用map代替写出来
"""
r=map(f1,list_x)
print(r)#<map object at 0x000000000BB93470>是一个对象
print(list(r))#[1, 4, 9, 16, 25, 36, 49, 64, 81]
###################################################################
"""
map与lambda
"""
list_x=[1,2,3,4,5,6,7,8,9]
def f1(x):
return x*x
r=map(f1,list_x)
print(r)#<map object at 0x000000000BB93470>是一个对象
print(list(r))#[1, 4, 9, 16, 25, 36, 49, 64, 81]
"""
map中的f1函数完全可以用lambda表达式写出来
"""
list_x=[1,2,3,4,5,6,7,8,9]
r=map(lambda x:x*x,list_x)
print(list(r))#[1, 4, 9, 16, 25, 36, 49, 64, 81]
"""
list_x
list_y
"""
list_x=[2,3,4]
list_y=[5,6,7]
r=map(lambda x,y:x*x+y,list_x,list_y)
print(list(r))#[9, 15, 23]
#特殊情况1
list_x=[2,3,4]
list_y=[5,6]
r=map(lambda x,y:x*x+y,list_x,list_y)
print(list(r))#[9, 15]
#特殊情况1
list_x=[3,4]
list_y=[5,6,7]
r=map(lambda x,y:x*x+y,list_x,list_y)
print(list(r))#[14, 22]
###################################################################
"""
map
映射
reduce
归约
连续计算,连续调用lambda
"""
from functools import reduce
list_x=[1,2,3,4,5]
r=reduce(lambda x,y:x+y,list_x)
print(r)#15
#(((1+2)+3)+4)+5
list_x=['1','2','3','4','5']
r=reduce(lambda x,y:x+y,list_x,'abc')
print(r)#abc12345
list_x=['1','2','3','4','5']
r=reduce(lambda x,y:x+y,'abc',list_x)
print(r)
#TypeError: can only concatenate list (not "str") to list
######################################################################
"""
filter
过滤
"""
#把数值为0的过滤掉
list_x=[1,0,2,5,0,0,6,0]
r=filter(lambda x:True if x!=0 else False,list_x)
print(r)#<filter object at 0x000000000BB5A6D8>
print(list(r))#[1, 2, 5, 6]
list_x=[1,0,2,5,0,0,6,0]
r=filter(lambda x:x,list_x)
print(list(r))#[1, 2, 5, 6]