Python_函数做字典的值

当需要用到3个及以上的if...elif...else时就要考虑该方法进行简化

通过将函数名称当做字典的值,利用字典的关键字查询,可以快速定位函数,进行执行

【场景】用户查询信息,输入fn查询,执行对应函数

复制代码
 1 # 简单用十个函数模拟查询函数
 2 def fun1():
 3     print("查询1")
 4 def fun2():
 5     print("查询2")
 6 def fun3():
 7     print("查询3")
 8 def fun4():
 9     print("查询4")
10 def fun5():
11     print("查询5")
12 def fun6():
13     print("查询6")
14 def fun7():
15     print("查询7")
16 def fun8():
17     print("查询8")
18 def fun9():
19     print("查询9")
20 def fun10():
21     print("查询10")
复制代码

传统方法 if...elif...elif...else(写起来很麻烦)

复制代码
choice = input("请输入查询内容fn:")
if choice == 'f1':
    fun1()
elif choice == 'f2':
    fun2()
elif choice == 'f3':
    fun3()
elif choice == 'f4':
    fun4()
elif choice == 'f5':
    fun5()
elif choice == 'f6':
    fun6()
else:
    fun10()

"""
请输入查询内容fn:f1
查询1

"""
复制代码

将函数当做字典的值

复制代码
# 创建字典
info = {'f1': fun1,
       'f2': fun2,
       'f3': fun3,
       'f4': fun4,
       'f5': fun5,
       'f6': fun6,
       'f7': fun7,
       'f8': fun8,
       'f9': fun9,
       'f10': fun10}
choice = input("请输入查询内容fn:")
info_value = info.get(choice)
print(info_value)
if info_value:
    info_value()
else:
    print('输入异常')
"""
请输入查询内容fn:f11
None
输入异常

"""
复制代码

获取字典中的value 使用get()函数,这样当关键字不存在时,返回的值的None,不会导致程序报错

【总结】遇到连续重复的代码编写时,要思考解决方法,提高编程效率,同时增加代码的可读性

posted on   wangxiaobei2019  阅读(3136)  评论(0编辑  收藏  举报

编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示