python中Switch/Case实现的示例代码


Posted in Python onNovember 09, 2017

学习Python过程中,发现没有switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现。所以不妨自己来实现Switch/Case功能。

使用if…elif…elif…else 实现switch/case

可以使用if…elif…elif..else序列来代替switch/case语句,这是大家最容易想到的办法。但是随着分支的增多和修改的频繁,这种代替方式并不很好调试和维护。

方法一

通过字典实现

def foo(var):
  return {
      'a': 1,
      'b': 2,
      'c': 3,
  }.get(var,'error')  #'error'为默认返回值,可自设置

方法二

通过匿名函数实现

def foo(var,x):
  return {
      'a': lambda x: x+1,
      'b': lambda x: x+2,
      'c': lambda x: x+3, 
  }[var](x)

方法三

通过定义类实现

参考Brian Beck通过类来实现Swich-case

# This class provides the functionality we want. You only need to look at
# this if you want to know how this works. It only needs to be defined
# once, no need to muck around with its internals.
class switch(object):
  def __init__(self, value):
    self.value = value
    self.fall = False

  def __iter__(self):
    """Return the match method once, then stop"""
    yield self.match
    raise StopIteration

  def match(self, *args):
    """Indicate whether or not to enter a case suite"""
    if self.fall or not args:
      return True
    elif self.value in args: # changed for v1.5, see below
      self.fall = True
      return True
    else:
      return False


# The following example is pretty much the exact use-case of a dictionary,
# but is included for its simplicity. Note that you can include statements
# in each suite.
v = 'ten'
for case in switch(v):
  if case('one'):
    print 1
    break
  if case('two'):
    print 2
    break
  if case('ten'):
    print 10
    break
  if case('eleven'):
    print 11
    break
  if case(): # default, could also just omit condition or 'if True'
    print "something else!"
    # No need to break here, it'll stop anyway

# break is used here to look as much like the real thing as possible, but
# elif is generally just as good and more concise.

# Empty suites are considered syntax errors, so intentional fall-throughs
# should contain 'pass'
c = 'z'
for case in switch(c):
  if case('a'): pass # only necessary if the rest of the suite is empty
  if case('b'): pass
  # ...
  if case('y'): pass
  if case('z'):
    print "c is lowercase!"
    break
  if case('A'): pass
  # ...
  if case('Z'):
    print "c is uppercase!"
    break
  if case(): # default
    print "I dunno what c was!"

# As suggested by Pierre Quentel, you can even expand upon the
# functionality of the classic 'case' statement by matching multiple
# cases in a single shot. This greatly benefits operations such as the
# uppercase/lowercase example above:
import string
c = 'A'
for case in switch(c):
  if case(*string.lowercase): # note the * for unpacking as arguments
    print "c is lowercase!"
    break
  if case(*string.uppercase):
    print "c is uppercase!"
    break
  if case('!', '?', '.'): # normal argument passing style also applies
    print "c is a sentence terminator!"
    break
  if case(): # default
    print "I dunno what c was!"

# Since Pierre's suggestion is backward-compatible with the original recipe,
# I have made the necessary modification to allow for the above usage.

查看Python官方:PEP 3103-A Switch/Case Statement

发现其实实现Switch Case需要被判断的变量是可哈希的和可比较的,这与Python倡导的灵活性有冲突。在实现上,优化不好做,可能到最后最差的情况汇编出来跟If Else组是一样的。所以Python没有支持。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
基于python实现微信模板消息
Dec 21 Python
Python中的sort()方法使用基础教程
Jan 08 Python
Python实现购物车功能的方法分析
Nov 10 Python
Python实现进程同步和通信的方法
Jan 02 Python
解决yum对python依赖版本问题
Jul 05 Python
基于python的selenium两种文件上传操作实现详解
Sep 19 Python
python 使用while写猜年龄小游戏过程解析
Oct 07 Python
关于python中plt.hist参数的使用详解
Nov 28 Python
Python实现井字棋小游戏
Mar 09 Python
Django web自定义通用权限控制实现方法
Nov 24 Python
浅谈Python类的单继承相关知识
May 12 Python
Python学习之os包使用教程详解
Mar 21 Python
在Python web中实现验证码图片代码分享
Nov 09 #Python
Python模糊查询本地文件夹去除文件后缀的实例(7行代码)
Nov 09 #Python
Python3.6 Schedule模块定时任务(实例讲解)
Nov 09 #Python
Python中scatter函数参数及用法详解
Nov 08 #Python
python实现人脸识别代码
Nov 08 #Python
python生成随机图形验证码详解
Nov 08 #Python
Python爬虫实例爬取网站搞笑段子
Nov 08 #Python
You might like
THINKPHP2.0到3.0有哪些改进之处
2015/01/04 PHP
JS 日期验证正则附asp日期格式化函数
2009/09/11 Javascript
jquery获取颜色在ie和ff下的区别示例介绍
2014/03/28 Javascript
Ajax局部更新导致JS事件重复触发问题的解决方法
2014/10/14 Javascript
jQuery中document与window以及load与ready 区别详解
2014/12/29 Javascript
详解微信小程序开发之——wx.showToast(OBJECT)的使用
2017/01/18 Javascript
原生javascript实现文件异步上传的实例讲解
2017/10/26 Javascript
Vue-Router实现组件间跳转的三种方法
2017/11/07 Javascript
vue项目常用组件和框架结构介绍
2017/12/24 Javascript
vue axios请求超时的正确处理方法
2018/04/02 Javascript
以v-model与promise两种方式实现vue弹窗组件
2018/05/21 Javascript
详解Angular6.0使用路由步骤(共7步)
2018/06/29 Javascript
jQuery AJAX 方法success()后台传来的4种数据详解
2018/08/08 jQuery
Vue数据绑定简析小结
2019/05/07 Javascript
bootstrap实现嵌套模态框的实例代码
2020/01/10 Javascript
Selenium执行Javascript脚本参数及返回值过程详解
2020/04/01 Javascript
node+vue实现文件上传功能
2020/05/28 Javascript
Python 获取新浪微博的最新公共微博实例分享
2014/07/03 Python
python端口扫描系统实现方法
2014/11/19 Python
python通过openpyxl生成Excel文件的方法
2015/05/12 Python
python模块之sys模块和序列化模块(实例讲解)
2017/09/13 Python
Python文本统计功能之西游记用字统计操作示例
2018/05/07 Python
Python生成短uuid的方法实例详解
2018/05/29 Python
Python的Lambda函数用法详解
2019/09/03 Python
Python Collatz序列实现过程解析
2019/10/12 Python
解决python Jupyter不能导入外部包问题
2020/04/15 Python
读取nii或nii.gz文件中的信息即输出图像操作
2020/07/01 Python
Lookfantastic俄罗斯:欧洲在线化妆品零售商
2019/08/06 全球购物
世嘉游戏英国官方商店:SEGA Shop UK
2019/09/20 全球购物
Auguste The Label官网:澳大利亚一家精品女装时尚品牌
2020/06/14 全球购物
工程师岗位职责
2013/11/08 职场文书
办加油卡单位介绍信
2014/01/09 职场文书
《厄运打不垮的信念》教学反思
2014/04/13 职场文书
桥梁工程专业求职信
2014/04/21 职场文书
群众路线教育实践活动民主生活会个人检查对照思想汇报
2014/10/04 职场文书
简单总结SpringMVC拦截器的使用方法
2021/06/28 Java/Android