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分析git log日志示例
Feb 27 Python
django model去掉unique_together报错的解决方案
Oct 18 Python
python爬取拉勾网职位数据的方法
Jan 24 Python
Python 新建文件夹与复制文件夹内所有内容的方法
Oct 27 Python
使用python绘制3维正态分布图的方法
Dec 29 Python
Python语言检测模块langid和langdetect的使用实例
Feb 19 Python
对python特殊函数 __call__()的使用详解
Jul 02 Python
在jupyter notebook 添加 conda 环境的操作详解
Apr 10 Python
Python Pandas 对列/行进行选择,增加,删除操作
May 17 Python
python rsa-oaep加密的示例代码
Sep 23 Python
python 用struct模块解决黏包问题
Nov 07 Python
Python基于unittest实现测试用例执行
Nov 25 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
js下函数般调用正则的方法附代码
2008/06/22 PHP
php使用exec shell命令注入的方法讲解
2013/11/12 PHP
PHP安装扩展mcrypt以及相关依赖项深入讲解
2021/03/04 PHP
WEB页子窗口(showModalDialog和showModelessDialog)使用说明
2009/10/25 Javascript
AppBaseJs 类库 网上常用的javascript函数及其他js类库写的
2010/03/04 Javascript
js css 实现遮罩层覆盖其他页面元素附图
2014/09/22 Javascript
JavaScript中具名函数的多种调用方式总结
2014/11/08 Javascript
jquery中radio checked问题
2015/03/16 Javascript
AngularJs ng-route路由详解及实例代码
2016/09/14 Javascript
angular实现表单验证及提交功能
2017/02/01 Javascript
JS实现table表格内针对某列内容进行即时搜索筛选功能
2018/05/11 Javascript
javascript实现考勤日历功能
2018/11/29 Javascript
bootstrap下拉分页样式 带跳转页码
2018/12/29 Javascript
vue elementui 实现搜索栏公共组件封装的实例代码
2020/01/20 Javascript
JavaScript中的this/call/apply/bind的使用及区别
2020/03/06 Javascript
详解js中的原型,原型对象,原型链
2020/07/16 Javascript
JavaScript获取时区实现过程解析
2020/09/24 Javascript
[32:39]完美世界DOTA2联赛循环赛 Forest vs Inki BO2第一场 11.04
2020/11/04 DOTA
Python编程实现删除VC临时文件及Debug目录的方法
2017/03/22 Python
python爬虫基本知识
2018/03/05 Python
Python提取频域特征知识点浅析
2019/03/04 Python
python获取指定日期范围内的每一天,每个月,每季度的方法
2019/08/08 Python
在PyTorch中Tensor的查找和筛选例子
2019/08/18 Python
CSS书写规范、顺序和命名规则
2014/03/06 HTML / CSS
UNDONE手表官网:世界领先的定制手表品牌
2018/11/13 全球购物
Yahoo-PHP面试题3
2012/01/14 面试题
请描述一下”is a”关系和”has a”关系
2015/02/03 面试题
与C++相比,Java中的数组有什么不同
2014/03/25 面试题
文员岗位职责
2013/11/09 职场文书
班主任2015新年寄语
2014/12/08 职场文书
舌尖上的中国观后感
2015/06/02 职场文书
大学新生入学感想
2015/08/07 职场文书
2016年大学生社区服务活动总结
2016/04/06 职场文书
Vue中使用import进行路由懒加载的原理分析
2022/04/01 Vue.js
python中mongodb包操作数据库
2022/04/19 Python
在 Python 中利用 Pool 进行多线程
2022/04/24 Python