python学习笔记 - lambda 与 dict
#============== lambda字典 =================== #替换多重 if.. elif fun_dict = { 'add' : lambda a,b : a+b, 'sub' : lambda a,b : a-b, 'mul' : lambda a,b : a*b, 'dev' : lambda a,b : a/b } operator = 'mul' a,b = 5,2 #通过key来调用lambda表达式进行计算, 替换多重if...elif...操作 result = fun_dict.get(operator)(a,b) print('{operator}运算, 计算结果:{result}'.format(operator=operator, result=result))
打印结果:
mul运算, 计算结果:10