#============== 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

相关文章:

  • 2022-12-23
  • 2021-08-19
  • 2021-12-29
  • 2022-12-23
  • 2021-11-02
  • 2021-09-28
  • 2021-07-17
  • 2021-05-06
猜你喜欢
  • 2022-12-23
  • 2021-12-07
  • 2022-12-23
  • 2018-08-27
  • 2021-08-30
  • 2022-12-23
  • 2021-12-12
相关资源
相似解决方案