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在hadoop上跑起来
Jan 27 Python
机器学习python实战之手写数字识别
Nov 01 Python
Windows 7下Python Web环境搭建图文教程
Mar 20 Python
python 将有序数组转换为二叉树的方法
Mar 26 Python
python实现控制COM口的示例
Jul 03 Python
django 自定义过滤器(filter)处理较为复杂的变量方法
Aug 12 Python
python爬虫之爬取百度音乐的实现方法
Aug 24 Python
Python 自动登录淘宝并保存登录信息的方法
Sep 04 Python
Python 可视化神器Plotly详解
Dec 26 Python
python获取字符串中的email
Mar 31 Python
Python matplotlib安装以及实现简单曲线的绘制
Apr 26 Python
python区块链持久化和命令行接口实现简版
May 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
php的字符串用法小结
2010/06/08 PHP
linux下删除7天前日志的代码(php+shell)
2011/01/02 PHP
解析php中的escape函数
2013/06/29 PHP
浅谈php正则表达式中的非贪婪模式匹配的使用
2014/11/25 PHP
php数组随机排序实现方法
2015/06/13 PHP
PHP Filter过滤器全面解析
2016/08/09 PHP
PHP简单留言本功能实现代码
2017/06/09 PHP
自动生成文章摘要的代码[JavaScript 版本]
2007/03/20 Javascript
给moz-firefox下添加IE方法和属性
2007/04/10 Javascript
Javascript中查找不以XX字符结尾的单词示例代码
2013/10/15 Javascript
实例分析js和C#中使用正则表达式匹配a标签
2014/11/26 Javascript
JavaScript动态修改网页元素内容的方法
2015/03/21 Javascript
jQuery使用addClass()方法给元素添加多个class样式
2015/03/26 Javascript
js+HTML5基于过滤器从摄像头中捕获视频的方法
2015/06/16 Javascript
jQuery原型属性和原型方法详解
2015/07/07 Javascript
jQuery遍历DOM节点操作之filter()方法详解
2016/04/14 Javascript
Vue 过渡(动画)transition组件案例详解
2017/01/22 Javascript
node.js中EJS 模板快速入门教程
2017/05/08 Javascript
jQuery Datatable 多个查询条件自定义提交事件(推荐)
2017/08/24 jQuery
关于jquery layui弹出层的使用方法
2018/04/21 jQuery
使用Vue组件实现一个简单弹窗效果
2018/04/23 Javascript
原生JavaScript实现弹幕组件的示例代码
2020/10/12 Javascript
Python设计模式编程中Adapter适配器模式的使用实例
2016/03/02 Python
Python pass详细介绍及实例代码
2016/11/24 Python
python的socket编程入门
2018/01/29 Python
Python3爬楼梯算法示例
2019/03/04 Python
解决python文件双击运行秒退的问题
2019/06/24 Python
pytorch .detach() .detach_() 和 .data用于切断反向传播的实现
2019/12/27 Python
pytorch 准备、训练和测试自己的图片数据的方法
2020/01/10 Python
通过实例解析python描述符原理作用
2020/01/22 Python
scrapy redis配置文件setting参数详解
2020/11/18 Python
基于Python-turtle库绘制路飞的草帽骷髅旗、美国队长的盾牌、高达的源码
2021/02/18 Python
新加坡网上化妆品店:Best Buy World
2018/05/18 全球购物
实验室的标语
2014/06/20 职场文书
2015元旦晚会主持词(开场白+结束语)
2014/12/14 职场文书
mysql字符串截取函数小结
2021/04/05 MySQL