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检测手机QQ在线状态的脚本代码
Feb 10 Python
Python2.x中文乱码问题解决方法
Jun 02 Python
基于Python Shell获取hostname和fqdn释疑
Jan 25 Python
Python中的defaultdict与__missing__()使用介绍
Feb 03 Python
怎么使用pipenv管理你的python项目
Mar 12 Python
PyCharm鼠标右键不显示Run unittest的解决方法
Nov 30 Python
django框架自定义模板标签(template tag)操作示例
Jun 24 Python
opencv-python 读取图像并转换颜色空间实例
Dec 09 Python
python 已知一个字符,在一个list中找出近似值或相似值实现模糊匹配
Feb 29 Python
Spring @Enable模块驱动原理及使用实例
Jun 23 Python
解决pycharm不能自动保存在远程linux中的问题
Feb 06 Python
Python 第三方库 openpyxl 的安装过程
Dec 24 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
Laravel构建即时应用的一种实现方法详解
2017/08/31 PHP
Jquery + Ajax调用webService实例代码(asp.net)
2010/08/27 Javascript
JavaSript中变量的作用域闭包的深入理解
2014/05/12 Javascript
ECMAScript5中的对象存取器属性:getter和setter介绍
2014/12/08 Javascript
jQuery简单实现遍历数组的方法
2015/04/14 Javascript
jquery实现漫天雪花飞舞的圣诞祝福雪花效果代码分享
2015/08/20 Javascript
jQuery使用$.ajax进行即时验证实例详解
2015/12/11 Javascript
分离与继承的思想实现图片上传后的预览功能:ImageUploadView
2016/04/07 Javascript
javascript中对Date类型的常用操作小结
2016/05/19 Javascript
利用angular.copy取消变量的双向绑定与解析
2016/11/25 Javascript
Bootstrap基本样式学习笔记之按钮(4)
2016/12/07 Javascript
浅谈Vue Element中Select下拉框选取值的问题
2018/03/01 Javascript
vue 路由嵌套高亮问题的解决方法
2018/05/17 Javascript
JS实现的判断方法、变量是否存在功能示例
2020/03/28 Javascript
vue项目前端埋点的实现
2019/03/06 Javascript
layui点击按钮页面会自动刷新的解决方案
2019/10/25 Javascript
[08:07]DOTA2每周TOP10 精彩击杀集锦vol.8
2014/06/25 DOTA
Python常用时间操作总结【取得当前时间、时间函数、应用等】
2017/05/11 Python
python实现手机通讯录搜索功能
2018/02/22 Python
一百行python代码将图片转成字符画
2021/02/19 Python
Python3中urlencode和urldecode的用法详解
2019/07/23 Python
使用pyecharts生成Echarts网页的实例
2019/08/12 Python
使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件及出现问题解决方法
2019/09/06 Python
详解基于python-django框架的支付宝支付案例
2019/09/23 Python
Python 实现顺序高斯消元法示例
2019/12/09 Python
Pandas时间序列重采样(resample)方法中closed、label的作用详解
2019/12/10 Python
Pytorch使用MNIST数据集实现基础GAN和DCGAN详解
2020/01/10 Python
Python使用扩展库pywin32实现批量文档打印实例
2020/04/09 Python
使用tensorflow实现VGG网络,训练mnist数据集方式
2020/05/26 Python
世界上最好的帽子:Tilley
2016/11/27 全球购物
伦敦最受欢迎的蛋糕店:Konditor & Cook
2019/11/01 全球购物
工商管理本科毕业生求职信范文
2013/10/05 职场文书
个人培训自我鉴定
2014/03/28 职场文书
2015年新农合工作总结
2015/03/30 职场文书
开业典礼致辞
2015/07/29 职场文书
土木工程生产实习心得体会
2016/01/22 职场文书