python 的 python中Switch/Case实现的示例代码

学习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)

方法三

通过定义类实现

参考通过类来实现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中case的用法_python中Switch/Case实现的示例代码相关推荐

  1. python 字典定义日志用法_python中字典(Dictionary)用法实例详解

    本文实例讲述了python中字典(Dictionary)用法.分享给大家供大家参考.具体分析如下: 字典(Dictionary)是一种映射结构的数据类型,由无序的"键-值对"组成. ...

  2. python中max函数用法_Python中max函数用法实例分析

    Python中max函数用法实例分析 更新时间:2015年07月17日 15:45:09 作者:优雅先生 这篇文章主要介绍了Python中max函数用法,实例分析了Python中max函数的功能与使用 ...

  3. python中print的用法_Python中print函数简单使用总结

    Python中print函数简单使用总结 print函数是Python的入门,每一个学习python的人都绕不开这个函数,下面介绍一下这个函数的用法. 打开电脑,选择python软件,下面选择pyth ...

  4. python常用函数的用法_python中常用函数整理

    1.map map是python内置的高阶函数,它接收一个函数和一个列表,函数依次作用在列表的每个元素上,返回一个可迭代map对象. class map(object):""&qu ...

  5. python中lambda()的用法_python中lambda()的用法

    在C++11和C#中都有匿名函数的存在.下面看看在python中匿名函数的使用. 1.lambda只是一个表达式,函数体比def简单很多. 2.lambda的主体是一个表达式,而不是一个代码块.仅仅能 ...

  6. [转载] python里字典的用法_python中字典(Dictionary)用法实例详解

    参考链接: Python字典dictionary copy方法 本文实例讲述了python中字典(Dictionary)用法.分享给大家供大家参考.具体分析如下: 字典(Dictionary)是一种映 ...

  7. python中replace的用法_python中replace的用法是什么?

    python中replace的用法是什么? Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次. r ...

  8. python中sleep函数用法_python中sleep函数用法实例分析

    本文实例讲述了python中sleep函数用法.分享给大家供大家参考.具体如下: Python中的sleep用来暂停线程执行,单位为秒 #------------------------------- ...

  9. python中sleep的用法_python中sleep函数用法实例分析

    本文实例讲述了python中sleep函数用法.分享给大家供大家参考.具体如下: Python中的sleep用来暂停线程执行,单位为秒 #------------------------------- ...

最新文章

  1. 微信硬件平台智能路由行业解决方案
  2. 推荐系统之基于邻域的算法-------协同过滤算法
  3. 关于你,关于我. 你好 5G
  4. Pyppeteer 使用笔记
  5. mysql 人名用什么类型_如何选择合适的MySQL数据类型
  6. 部署java项目_企业最看重什么样的Java人才?
  7. ASP.NET2.0 菜单控件menu的动态静态用法
  8. PHP学习笔记 - 在Eclipse中使用XDebug调试代码 | Using XDebug debug code in eclipse
  9. numpy 矩阵 秩_一文读懂 NumPy 及应用
  10. 有道Java_有道词典java版下载-有道词典java豪华版v1.0.7 安卓版 - 极光下载站
  11. 海思Hi3796MV200最新官方SDK
  12. CTF必备取证神器(volatility、PTF、取证大师、Magnet AXIOM)
  13. Mybatis复习1——B站
  14. 安卓毕业设计选题基于Uniapp实现的Android的校园二手商品交易平台
  15. 3D灯光教程仅需三个步骤,用ThingJS体验极速开发!
  16. CAD中怎么画指北针?CAD画指北针教程
  17. python下复制文件并重命名
  18. 全球与中国便帽市场深度研究分析报告
  19. window在文件管理器中打开命令行窗口
  20. 计算机硬件故障检测实验报告,计算机系统的硬件检测实验报告

热门文章

  1. delphi开发日志——基窗体,使用面向对象编程的编程思想创建基类
  2. 大话设计模式—建造者模式
  3. iptables规则备份和恢复 firewalld服务
  4. 【特征选择】基础知识
  5. spring bean 小记
  6. centos7修改默认网卡名称
  7. Creating UIImage with renderingMode in Swift
  8. scrapy 的三个入门应用场景
  9. 一个数据应用闭环(转载)
  10. HDU 1536 求解SG函数