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 相关文章推荐
利用一个简单的例子窥探CPython内核的运行机制
Mar 30 Python
Python实现数通设备端口使用情况监控实例
Jul 15 Python
python使用xpath中遇到:到底是什么?
Jan 04 Python
OPENCV去除小连通区域,去除孔洞的实例讲解
Jun 21 Python
Python设计模式之外观模式实例详解
Jan 17 Python
python+selenium实现简历自动刷新的示例代码
May 20 Python
使用python写的opencv实时监测和解析二维码和条形码
Aug 14 Python
解决pyshp UnicodeDecodeError的问题
Dec 06 Python
TensorFlow命名空间和TensorBoard图节点实例
Jan 23 Python
使用wxpy实现自动发送微信消息功能
Feb 28 Python
python 实现读取csv数据,分类求和 再写进 csv
May 18 Python
Python collections.defaultdict模块用法详解
Jun 18 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实现小型站点广告管理(修正版)
2006/10/09 PHP
php下批量挂马和批量清马代码
2011/02/27 PHP
在Laravel5.6中使用Swoole的协程数据库查询
2018/06/15 PHP
IE6不能修改NAME问题的解决方法
2010/09/03 Javascript
javascript返回顶部效果(自写代码)
2013/01/06 Javascript
javascript中数组中求最大值示例代码
2013/12/18 Javascript
通过JS动态创建一个html DOM元素并显示
2014/10/15 Javascript
Javascript aop(面向切面编程)之around(环绕)分析
2015/05/01 Javascript
基于jQuery+Cookie实现的防止刷新的在线考试倒计时
2015/06/19 Javascript
Jquery easyui 实现动态树
2015/11/17 Javascript
浅谈JS函数定义方式的区别
2016/10/30 Javascript
深入理解ES6 Promise 扩展always方法
2017/09/26 Javascript
fetch 使用及如何接收JS传值
2017/11/11 Javascript
关于vue中 $emit的用法详解
2018/04/12 Javascript
jQuery实现table表格信息的展开和缩小功能示例
2018/07/21 jQuery
Koa 使用小技巧(小结)
2018/10/22 Javascript
vue实现路由懒加载及组件懒加载的方式
2019/06/11 Javascript
原生JS实现相邻月份日历
2020/10/13 Javascript
python调用Moxa PCOMM Lite通过串口Ymodem协议实现发送文件
2014/08/15 Python
Python反射的用法实例分析
2018/02/11 Python
基于随机梯度下降的矩阵分解推荐算法(python)
2018/08/31 Python
Python3最长回文子串算法示例
2019/03/04 Python
pytorch 实现打印模型的参数值
2019/12/30 Python
tensorflow实现残差网络方式(mnist数据集)
2020/05/26 Python
PythonPC客户端自动化实现原理(pywinauto)
2020/05/28 Python
Django ORM判断查询结果是否为空,判断django中的orm为空实例
2020/07/09 Python
基于python实现生成指定大小txt文档
2020/07/20 Python
法国时尚童装网站:Melijoe
2016/08/10 全球购物
家乐福巴西网上超市:Carrefour巴西
2016/10/31 全球购物
英国在线电子和小工具商店:TecoBuy
2018/10/06 全球购物
美国最大的烧烤架和户外生活用品专业零售商:Barbeques Galore
2021/01/09 全球购物
煤矿班组长岗位职责
2013/12/29 职场文书
改作风抓落实促发展心得体会
2014/09/10 职场文书
2015新员工试用期工作总结
2014/12/12 职场文书
话题作文之诚信
2019/11/28 职场文书
php远程请求CURL案例(爬虫、保存登录状态)
2021/04/01 PHP