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定时器(Timer)用法简单实例
Jun 04 Python
Python环境下安装使用异步任务队列包Celery的基础教程
May 07 Python
Pycharm技巧之代码跳转该如何回退
Jul 16 Python
flask使用session保存登录状态及拦截未登录请求代码
Jan 19 Python
详解python中的线程
Feb 10 Python
python用opencv批量截取图像指定区域的方法
Jan 24 Python
Django Admin中增加导出Excel功能过程解析
Sep 04 Python
解决Python使用列表副本的问题
Dec 19 Python
Python计算机视觉里的IOU计算实例
Jan 17 Python
基于python生成英文版词云图代码实例
May 16 Python
matplotlib源码解析标题实现(窗口标题,标题,子图标题不同之间的差异)
Feb 22 Python
如何正确理解python装饰器
Jun 15 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 获取当前访问的url文件名的方法小结
2010/02/08 PHP
PHP模块 Memcached功能多于Memcache
2011/06/14 PHP
session在php5.3中的变化 session_is_registered() is deprecated in
2013/11/12 PHP
PHP 正则判断中文UTF-8或GBK的思路及具体实现
2013/11/26 PHP
ThinkPHP3.2.2的插件控制器功能
2015/03/05 PHP
PHP多线程编程之管道通信实例分析
2015/03/07 PHP
Avengerls vs KG BO3 第一场2.18
2021/03/10 DOTA
在b/s开发中经常用到的javaScript技术
2006/08/23 Javascript
javascript编程起步(第五课)
2007/01/10 Javascript
javascript Zifa FormValid 0.1表单验证 代码打包下载
2007/06/08 Javascript
JavaScript初学者需要了解10个小技巧
2010/08/25 Javascript
js输出阴历、阳历、年份、月份、周示例代码
2014/01/29 Javascript
javascript实现手机震动API代码
2015/08/05 Javascript
JavaScript生成SQL查询表单的方法
2015/08/13 Javascript
Bootstrap框架结合jQuery仿百度换肤功能实例解析
2016/09/17 Javascript
vue 中swiper的使用教程
2018/05/22 Javascript
React中如何引入Angular组件详解
2018/08/09 Javascript
elementUI多选框反选的实现代码
2019/04/03 Javascript
让mocha支持ES6模块的方法实现
2020/01/14 Javascript
Python实现从URL地址提取文件名的方法
2015/05/15 Python
Python实现PS滤镜特效Marble Filter玻璃条纹扭曲效果示例
2018/01/29 Python
Python图像处理之识别图像中的文字(实例讲解)
2018/05/10 Python
解决python matplotlib imshow无法显示的问题
2018/05/24 Python
django 使用全局搜索功能的实例详解
2019/07/18 Python
基于python实现从尾到头打印链表
2019/11/02 Python
在Python中等距取出一个数组其中n个数的实现方式
2019/11/27 Python
css3的图形3d翻转效果应用示例
2014/04/08 HTML / CSS
使用HTML5在网页中嵌入音频和视频播放的基本方法
2016/02/22 HTML / CSS
农场厂长岗位职责
2013/12/28 职场文书
迎新晚会主持词
2014/03/24 职场文书
委托书范文
2014/04/02 职场文书
技术比武方案
2014/05/19 职场文书
电大奖学金获奖感言
2014/08/14 职场文书
反腐倡廉影片观后感
2015/06/08 职场文书
争做文明公民倡议书
2019/06/24 职场文书
小学四年级作文之写景
2019/08/23 职场文书