python中Switch/Case实现
学习Python过程中,发现没有switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现。所以不妨自己来实现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没有支持。
在业务上Switch/Case和If-elif实现优化上究竟最差是如何?有体会的童鞋欢迎评论分享探讨哈!O(∩_∩)O
python中Switch/Case实现的更多相关文章
- Python里如何实现C中switch...case的功能
python没有switch case 不过可以通过建立字典实现类似的功能 例子:根据输入的年月日,判断是该年中的第几天 y = int(input('请输入年:')) m = int(input(' ...
- Why Doesn't Python Have Switch/Case?
Why Doesn't Python Have Switch/Case? Tuesday, June 09, 2015 (permalink) Unlike every other programmi ...
- Javascript 中 switch case 等于 (== )还是 恒等于(===)?
Javascript 中 switch case 等于 (== )还是 恒等于(===)? 可以测试一下以下代码,这个 case 中是 等于(==)还是恒等于(===) <script> ...
- python技巧 switch case语句
不同于C语言和SHELL,python中没有switch case语句,关于为什么没有,官方的解释是这样的 使用Python模拟实现的方法: def switch_if(fun, x, y): ...
- asp.net ashx处理程序中switch case的替代方案总结
目录 1.用委托字典代替switch...case; 2.利用反射替代switch...case: 3.比较两种方案 4.其他方案 4.说明 5.参考 在开发 asp.net 项目中,通常使用一般处理 ...
- Python中Swithch Case语法实现
而python本身没有switch语句,解决方法有以下3种:A.使用dictionaryvalues = { value1: do_some_stuff1, value2: do_some_stuff ...
- js中switch/case分支的值可以是变量或表达式
在一些高级语言如C#中,switch分支的值只能是常量,而js中可以是变量或表达式: <!DOCTYPE html> <html lang="en"> &l ...
- thymeleaf中switch case多出一个空行
以下是<thymeleaf3.0.5中文参考手册.pdf>中的代码,官方代码没有具体去查询. <div th:switch="${user.role}"> ...
- C# 中Switch case 返回不止用break
Switch(temp) { case "A": //跳出循环 break; case "B": //返回值 return var; case "C& ...
随机推荐
- solidity学习-cryptoPunks为实例
在这里使用cryptoPunks为实例来进行solidity的介绍,一般这些内容理解了就能够进行相对简单的智能合约的编写了,同时会添加一些我认为也十分重要的内容学习文档为http://solidity ...
- #ifdef __cplusplus extern "C" { #endif”的定义
平时我们在linux c平台开发的时候,引用了一些Cpp或者C的代码库,发现一些头文件有如下代码条件编译. #ifdef __cplusplus extern "C" { #e ...
- Android 由 android:launchMode="singleInstance“引发的界面无法返回的情况
问题描述:现有A.B.C三个Activity.现在A跳转到B再由B跳转到C,然后依次返回.正常情况是C先返回B然后再返回的A.但现在的情况是C直接跳过B直接返回到A了. 解决办法:认真排查了A.B.C ...
- 每个大主播都是满屏弹幕,怎么做到的?Python实战无限刷弹幕!
anmu 是一个开源的直播平台弹幕接口,使用他没什么基础的你也可以轻松的操作各平台弹幕.使用不到三十行代码,你就可以使用Python基于弹幕进一步开发.支持斗鱼.熊猫.战旗.全民.Bilibili多平 ...
- 表单验证(AngularJs)
这次,学习angularjs的表单的验证,angularjs提供上表几种状态验证: 状态 描述 $invalid 未通过验证 $valid 经过验证 $pristine 未修改过 $dirty 修改 ...
- sql server2016里面的json功能 - 转
测试一下基本的,从查询结果里面构造一个json 的格式 create table t1(ID int identity,name nvarchar(50),Chinese int ,Math int) ...
- Ionic 部分手机升级不成功的问题
Android端的手机App发布之后的一段时间,用户反馈App无法升级的情况. 原因分析: 对代码进行错误在线,提示是FileNOTFindException错误,确定是下载的时候保存的目的路径 不存 ...
- 大话设计模式:代理模式 C#
学无止境,精益求精 十年河东,十年河西,莫欺少年穷 学历代表你的过去,能力代表你的现在,学习代表你的将来 所谓代理模式就是你去委托一个人帮你干一件事!例如:你委托我帮你谈恋爱,你委托我帮你陪你媳妇儿逛 ...
- 全自动数据表格JQuery版
由于最近工作上有些变动,已经快一个月没有写博客了.上一篇博客[React]全自动数据表格组件——BodeGrid介绍了全自动数据表格的设计思路以及分享了一个react.js的实现.但是现实情况中为了节 ...
- JAVA消息确认机制之ACK模式
JMS API中约定了Client端可以使用四种ACK模式,在javax.jms.Session接口中: AUTO_ACKNOWLEDGE = 1 自动确认 CLIENT_ACKNOWLEDGE ...