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中条件选择和循环语句使用方法介绍
Mar 13 Python
Python学生成绩管理系统简洁版
Apr 05 Python
用TensorFlow实现lasso回归和岭回归算法的示例
May 02 Python
python绘制直线的方法
Jun 30 Python
python实现朴素贝叶斯算法
Nov 19 Python
python实现爬山算法的思路详解
Apr 09 Python
Python 函数list&read&seek详解
Aug 28 Python
解决pycharm启动后总是不停的updating indices...indexing的问题
Nov 27 Python
Django REST framwork的权限验证实例
Apr 02 Python
浅谈优化Django ORM中的性能问题
Jul 09 Python
Python爬虫之Selenium鼠标事件的实现
Dec 04 Python
python中的对数log函数表示及用法
Dec 09 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
php网页后退不再出现过期
2007/03/08 PHP
部署PHP时的4个配置修改说明
2015/10/19 PHP
YiiFramework入门知识点总结(图文教程)
2015/12/28 PHP
tp5递归 无限级分类详解
2019/10/18 PHP
php 使用 __call实现重载功能示例
2019/11/18 PHP
Javascript 调试利器 Firebug使用详解六
2009/07/05 Javascript
js如何判断不同系统的浏览器类型
2013/10/28 Javascript
事件委托与阻止冒泡阻止其父元素事件触发
2014/09/02 Javascript
JS实现至少包含字母、大小写数字、字符的密码等级的两种方法
2015/02/03 Javascript
JQuery动态添加和删除表格行的方法
2015/03/09 Javascript
使用AngularJS 应用访问 Android 手机的图片库
2015/03/24 Javascript
JavaScript中setUTCMilliseconds()方法的使用详解
2015/06/12 Javascript
每天一篇javascript学习小结(面向对象编程)
2015/11/20 Javascript
JavaScript数据存储 Cookie篇
2016/07/02 Javascript
Bootstrap表单使用方法详解
2017/02/17 Javascript
webpack2.0搭建前端项目的教程详解
2017/04/05 Javascript
Vue 实用分页paging实例代码
2017/04/12 Javascript
js实现简易聊天对话框
2017/08/17 Javascript
javascript Function函数理解与实战
2017/12/01 Javascript
Vue2.0 实现歌手列表滚动及右侧快速入口功能
2018/08/08 Javascript
一篇文章带你浅入webpack的DLL优化打包
2020/02/20 Javascript
JavaScript观察者模式原理与用法实例详解
2020/03/10 Javascript
Python构造自定义方法来美化字典结构输出的示例
2016/06/16 Python
Python脚本处理空格的方法
2016/08/08 Python
Python 多进程和数据传递的理解
2017/10/09 Python
Python基础之文件读取的讲解
2019/02/16 Python
使用pyqt5 tablewidget 单元格设置正则表达式
2019/12/13 Python
八年级语文教学反思
2014/02/11 职场文书
关于环保的演讲稿
2014/05/10 职场文书
党员批评与自我批评思想汇报
2014/10/08 职场文书
施工员岗位职责范本
2015/04/11 职场文书
幼儿园开学家长寄语(2015秋季)
2015/05/27 职场文书
信用卡工作证明范本
2015/06/19 职场文书
巴黎圣母院读书笔记
2015/06/26 职场文书
2016年猴年新春致辞
2015/08/01 职场文书
孕妇病假条怎么写
2015/08/17 职场文书