python中Switch/Case实现的示例代码
作者:gerrydeng 发布时间:2021-09-18 22:03:39
标签: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)
方法三
通过定义类实现
参考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没有支持。
来源:http://www.cnblogs.com/gerrydeng/p/7191927.html


猜你喜欢
- 如下所示:(x,y)为要转的点,(pointx,pointy)为中心点,如果顺时针角度为anglesrx = (x-pointx)*cos(
- 1.0 新建项目1.1 初始化项目输入npm init,之后需要填什么就写什么新建src目录,并在src目录下新建alert.vue$ np
- 插件编写的基本方法推荐大家先看看官方给出的插件使用和开发方法https://vuejs.bootcss.com/guide/plugins.
- Git合并分支后,需要将子分支提交到git仓库,这个时候就需要单独提交子分支,其步骤如下:1.先创建子分支,并包含最新当前分支下的修改数据g
- 1. 类的继承与方法的重载上面就是先定义了一个类A,然后由定义了一个类B,B继承了类A,这样B就有了A的非私有属性和方法。class Was
- 使用命令行搭建单页面应用我们来看一下最后完成的效果:大纲1. 下载 node, git, npm2. 使用命令行安装一个项目一、 下载工具n
- 1、改表法。可能是你的帐号不允许从远程登陆,只能在localhost。这个时候只要在localhost的那台电脑,登入mysql后,更改&n
- 上节基本完成了SVM的理论推倒,寻找最大化间隔的目标最终转换成求解拉格朗日乘子变量alpha的求解问题,求出了alpha即可求解出SVM的权
- 一般情况下,mysql会默认提供多种存储引擎,可以通过下面的查看:1)查看mysql是否安装了innodb插件。通过下面的命令结果可知,已经
- 本文实例讲述了python实现在字符串中查找子字符串的方法。分享给大家供大家参考。具体如下:这里实现python在字符串中查找子字符串,如果
- 前言这篇文章主要介绍了Python 字符串去除空格的6种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,来
- 先说点什么mybatis-plus是一款增强版的mybatis,功能强大,可以很大程度的简化开发。然而达梦数据库比较小众,虽然官方说myba
- PyCharm是Python著名的Python集成开发环境(IDE)conda有Miniconda和Anaconda,前者应该是类似最小化版
- 任何一个交互过程的操作,对于用户来说都有学习成本,谁也不能保证所有人都可以准确无误地走完一个流程。交互设计师在设计时应该考虑适时地给用户相应
- nofollow标签是Google2005年推出的,目的是尽量减少垃圾链接对搜索引擎的影响。有用过网页制作工具的人都知道,在这些工具里是找不
- 这次要为我的python程序加上数据库,主要是实现从mysql中查询出数据并在页面上显示出来。首先是mysql的配置文件config.pyh
- 简介Pycharm安装以后必须激活后,才能正常的使用。否则就不能使用。【激活码激活】修改hosts文件添加下面一行到hosts文件,目的是屏
- 一、读取整个文件内容在读取文件之前,我们先创建一个文本文件resource.txt作为源文件。resource.txtmy name is
- 前言前面我们介绍了 pandas 的基础语法操作,下面我们开始介绍 pandas 的数据读写操作。pandas 的 IO API 是一组顶层
- 一、Pycharm下载与安装附:Python、Pycharm和Anaconda的关系:Python是一种解释型、面向对象、动态数据类型的高级