【python函数】lambda,reduce,map,filter
作者:互联网
lambda匿名函数
#求圆形的面积
import math
def fun_cir(r):
s = math.pi*r*r
return s
print(f"s={fun_cir(3)}")
print(lambda r:math.pi*7*8) # 报错,<function <lambda> at 0x00000205945E3D90>
result = lambda r:math.pi*r*r
result(4)
def fun_caculate(o):
if o == '+':
return lambda a,b: a+b
elif o =='-':
return lambda a,b:a-b
elif o == '*':
return lambda a,b:a*b
elif o == '/':
return lambda a,b:a/b
# f接受fun函数传参后的返回值
f = fun_caculate("+")
# 返回值是一个lambda函数,因此还要传参
print(f"f={f(3,4)}")
goods_info = [
("水杯",12.5,35),
("西装",1290,6666),
("电脑",7800,13800),
("摄像头",258.8,450)
]
goods_info.sort(key = lambda x: x[1]/x[2])
print(goods_info)
小结:
lambda是匿名函数,可以使程序看起来更简洁
lambda输出时,需要有一变量接收,不然报错<function <lambda> at 0x00000205945E3D90>
map函数
def cal_pro(e): if "红莲斗篷" == e: return "防御+120" elif "魔女斗篷" ==e: return "魔法防御+360" elif "影忍之足" == e: return "移动速度+60" elif "辉月" == e: return "无敌1.5s" elif "破军" ==e: return "破烂!" hero_o = [ "红莲斗篷", "魔女斗篷", "影忍之足", "辉月", "破军" ] p = map(cal_pro,hero_o) print(p) print(list(p))
lis = ['1','a','e']
p = map(lambda x:x.upper(),lis)
print(list(p))
小结:
map函数直接输出时,返回的是迭代器iterator类型,要list转换
在python2,map函数返回是列表list类型;在python3中,map函数返回是iterator类型
reduce函数
# 使用reduce函数之前要导包 from functools import reduce lis = [2,3,5] # reduce 有点类似于累积乘除加减什么的 p = reduce(lambda x,y: x+y, lis) print(p) p1 = reduce(lambda x,y: x*y, lis,4) print(p1)
小结:
filter函数
string = 'A b I F e' lis = string.split(' ') print(lis) str_up = filter(lambda x:x == x.upper(),lis) print(list(str_up)) lis = ['拜月','拜拜了您勒','图图','牛爷爷'] print(list(filter(lambda x:x.startswith('拜'), lis)))
标签:map,elif,return,函数,python,reduce,lis,print,lambda 来源: https://www.cnblogs.com/sdr900/p/16379441.html