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实现目录树生成示例
Mar 28 Python
简单理解Python中基于生成器的状态机
Apr 13 Python
Python计算斗牛游戏概率算法实例分析
Sep 26 Python
python中的随机函数小结
Jan 27 Python
Python实现发送与接收邮件的方法详解
Mar 28 Python
Python 实现中值滤波、均值滤波的方法
Jan 09 Python
Python 支付整合开发包的实现
Jan 23 Python
Django框架验证码用法实例分析
May 10 Python
Python 给定的经纬度标注在地图上的实现方法
Jul 05 Python
python 3.74 运行import numpy as np 报错lib\site-packages\numpy\__init__.py
Oct 06 Python
Python中pyecharts安装及安装失败的解决方法
Feb 18 Python
python实现在线翻译功能
Mar 03 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
phpfans留言版用到的install.php
2007/01/04 PHP
推荐十款免费 WordPress 插件
2015/03/24 PHP
详解WordPress中简码格式标签编写的基本方法
2015/12/22 PHP
javascript string字符串优化问题
2011/07/31 Javascript
js 浏览器事件介绍
2012/03/30 Javascript
JS简单实现元素复制示例附图
2013/11/19 Javascript
Linux下使用jq友好的打印JSON技巧分享
2014/11/18 Javascript
JS实现的表格行上下移动操作示例
2016/08/03 Javascript
微信小程序 限制1M的瘦身技巧与方法详解
2017/01/06 Javascript
浅谈jQuery框架Ajax常用选项
2017/07/08 jQuery
如何解决.vue文件url引用文件的问题
2019/01/18 Javascript
微信小程序 自定义复选框实现代码实例
2019/09/04 Javascript
Websocket 向指定用户发消息的方法
2020/01/09 Javascript
微信小程序仿通讯录功能
2020/04/09 Javascript
vue-以文件流-blob-的形式-下载-导出文件操作
2020/08/07 Javascript
JavaScript大数相加相乘的实现方法实例
2020/10/18 Javascript
python实现apahce网站日志分析示例
2014/04/02 Python
Python实现希尔排序算法的原理与用法实例分析
2017/11/23 Python
numpy找出array中的最大值,最小值实例
2018/04/03 Python
Django中使用Celery的方法示例
2018/11/29 Python
如何在Python中实现goto语句的方法
2019/05/18 Python
python Matplotlib底图中鼠标滑过显示隐藏内容的实例代码
2019/07/31 Python
Python Subprocess模块原理及实例
2019/08/26 Python
python子线程退出及线程退出控制的代码
2019/10/16 Python
python安装dlib库报错问题及解决方法
2020/03/16 Python
Pytorch 高效使用GPU的操作
2020/06/27 Python
socket.io 和canvas 实现的共享画板功能
2019/05/22 HTML / CSS
网络工程系信息安全技术专业大学生求职信
2013/10/22 职场文书
班主任寄语大全
2014/04/04 职场文书
公司演讲稿开场白
2014/08/25 职场文书
农民工预备党员思想汇报
2014/09/14 职场文书
教师节主持词开场白
2015/05/29 职场文书
html实现随机点名器的示例代码
2021/04/02 Javascript
详解JVM系列之内存模型
2021/06/10 Javascript
在 Python 中利用 Pool 进行多线程
2022/04/24 Python
MySQL中dd::columns表结构转table过程及应用详解
2022/09/23 MySQL