不香不帅的个人主页

最后更新:2026-02-05
原创 Python优化的分支处理方法
浏览: 119

编程语言中分支是使用率最高的一种语言结构,Python当然也不例外。所有编程语言中无外乎是if、else、switch、case等关键字来实现。Python3.10之前,python是不支持多重分支操作的,只提供了if 、else和elif。如果选择比较多的情况下,用起来就不是很方便。在此,列举出三种Python分支的处理方式,仅供参考:

1、原始 if else 处理方式

if val==1:
  print("option1")
elif val==2:
  print("option2")
elif val==3:
  print("option2")
else:
  print("default option")

这是最原始的方式,在此就不用详细说明了。


2、字典映射方式

def switch(optionkey:str):
  case = {
    "option1": "value1",
    "option2": "value2",
    "option3": "value3"
  }
  return case.get(optionkey,"default value")
  
 print(switch("opiton1"))

这是一个简单的映射,利用字典的键值和无对应键时返回默认值的方式实现switch功能。


3、字典函数映射

def executor1(p:str)->str:
  return f"value1 {p}"
   
def executor2(p:str)->str:
  return f"value2 {p}"
  
def executor_default(p:str)->str:
  return f"default {p}"
  
def switch(optionkey:str)->str:
  case = {
    "option1":executor1,
    "option2":executor2
    }
   return case.get(optionkey,executor_default)()

这种方式和第2中有些类似,但是case 字典里面是的值是指向一个函数。case.get(optionkey,executor_default)() 这一句后面的括号不能省略,如果省略只是返回了函数指针,而非去执行这个函数。


4、Python3.10后的match操作

match day:
  case "monday"|"friday":
     print("want to die")
   case "sunday":
     print("happy day")
   _:
     print(f"{day}")

这种结构,与C#、Java、C、C++等语言类似,_ 表示default选项。


提醒:原创不易,如果您需要转载本文。为表对本人的尊重烦请标注出本文的出处。内容包括:作者和本文链接。可直接复制以下内容:

原文作者:<a href='http://www.hn-lxm.com' target="_blank">不香不帅</a>

原文链接: <a href='http://www.hn-lxm.com/article/V2lsbGlhbTM4TGVl.html' title='Python优化的分支处理方法' target="_blank">Python优化的分支处理方法</a>

评论