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中使用urllib2防止302跳转的代码例子
Jul 07 Python
Python中asyncore异步模块的用法及实现httpclient的实例
Jun 28 Python
Python 遍历列表里面序号和值的方法(三种)
Feb 17 Python
python实现二叉树的遍历
Dec 11 Python
Pandas 数据处理,数据清洗详解
Jul 10 Python
TensorFlow实现iris数据集线性回归
Sep 07 Python
使用GitHub和Python实现持续部署的方法
May 09 Python
Python3操作Excel文件(读写)的简单实例
Sep 02 Python
python 实现turtle画图并导出图片格式的文件
Dec 07 Python
Python配置pip国内镜像源的实现
Aug 20 Python
Python实现曲线拟合的最小二乘法
Feb 19 Python
matplotlib绘制正余弦曲线图的实现
Feb 22 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实现utf-8和GB2312编码相互转换函数代码
2013/02/07 PHP
解析如何通过PHP函数获取当前运行的环境 来进行判断执行逻辑(小技巧)
2013/06/25 PHP
非常实用的php弹出错误警告函数扩展性强
2014/01/17 PHP
JavaScript中继承的一些示例方法与属性参考
2010/08/07 Javascript
IE事件对象(The Internet Explorer Event Object)
2012/06/27 Javascript
JavaScript splice()方法详解
2020/09/22 Javascript
javascript实现回车键提交表单方法总结
2015/01/10 Javascript
VUE实现日历组件功能
2017/03/13 Javascript
Angularjs根据json文件动态生成路由状态的实现方法
2017/04/17 Javascript
webpack-dev-server远程访问配置方法
2018/02/22 Javascript
JS散列表碰撞处理、开链法、HashTable散列示例
2019/02/08 Javascript
Vue v-bind动态绑定class实例方法
2020/01/15 Javascript
JavaScript事件概念详解(区分静态注册和动态注册)
2021/02/05 Javascript
Python+微信接口实现运维报警
2016/08/27 Python
Python从数据库读取大量数据批量写入文件的方法
2018/12/10 Python
详解Python基础random模块随机数的生成
2019/03/23 Python
基于python分析你的上网行为 看看你平时上网都在干嘛
2019/08/13 Python
win10下opencv-python特定版本手动安装与pip自动安装教程
2020/03/05 Python
python实现飞船游戏的纵向移动
2020/04/24 Python
猫途鹰英国网站:TripAdvisor英国(旅游社区和旅游评论)
2016/08/30 全球购物
美国宠物护理专家:Revival Animal Health
2020/01/05 全球购物
软件工程专业推荐信
2013/10/28 职场文书
英文自荐信
2013/12/19 职场文书
聊城大学毕业生自荐书
2014/02/01 职场文书
党支部书记岗位责任制
2014/02/11 职场文书
销售总经理岗位职责
2014/03/15 职场文书
个人贷款担保书
2014/04/01 职场文书
拔河比赛口号
2014/06/10 职场文书
大学新生军训自我鉴定范文
2014/09/13 职场文书
2014年9.18纪念日演讲稿
2014/09/14 职场文书
房屋财产继承协议书范本
2014/11/03 职场文书
2015年学校安全工作总结
2015/04/22 职场文书
小学生光盘行动倡议书
2015/04/28 职场文书
2015年社区反邪教工作总结
2015/10/14 职场文书
Python爬虫之爬取某文库文档数据
2021/04/21 Python
Django项目如何获得SSL证书与配置HTTPS
2021/04/30 Python