Python如何使用函数做字典的值

yipeiwu_com6年前Python基础

这篇文章主要介绍了Python如何使用函数做字典的值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

当需要用到3个及以上的if...elif...else时就要考虑该方法进行简化
通过将函数名称当做字典的值,利用字典的关键字查询,可以快速定位函数,进行执行

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

# 简单用十个函数模拟查询函数
def fun1():
  print("查询1")
def fun2():
  print("查询2")
def fun3():
  print("查询3")
def fun4():
  print("查询4")
def fun5():
  print("查询5")
def fun6():
  print("查询6")
def fun7():
  print("查询7")
def fun8():
  print("查询8")
def fun9():
  print("查询9")
def fun10():
  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,不会导致程序报错

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现搜索文本文件内容脚本

python实现搜索文本文件内容脚本

本文介绍用python实现的搜索本地文本文件内容的小程序。从而学习Python I/O方面的知识。代码如下: import os #根据文件扩展名判断文件类型 def endWit...

利用Python操作消息队列RabbitMQ的方法教程

前言 RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统。他遵循Mozilla Public License开源协议。 MQ全称为Message Queue, 消息队列(...

python实现简单socket程序在两台电脑之间传输消息的方法

本文实例讲述了python实现简单socket程序在两台电脑之间传输消息的方法。分享给大家供大家参考。具体分析如下: python开发简单socket程序在两台电脑之间传输消息,分为客户...

Python常用模块logging——日志输出功能(示例代码)

用途 logging模块是Python的内置模块,主要用于输出运行日志,可以灵活配置输出日志的各项信息。 基本使用方法 logging.basicConfig(level=loggi...

使用python 的matplotlib 画轨道实例

使用python 的matplotlib 画轨道实例

如下所示: import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpa...