学习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实现的更多相关文章

  1. Python里如何实现C中switch...case的功能

    python没有switch case 不过可以通过建立字典实现类似的功能 例子:根据输入的年月日,判断是该年中的第几天 y = int(input('请输入年:')) m = int(input(' ...

  2. Why Doesn't Python Have Switch/Case?

    Why Doesn't Python Have Switch/Case? Tuesday, June 09, 2015 (permalink) Unlike every other programmi ...

  3. Javascript 中 switch case 等于 (== )还是 恒等于(===)?

    Javascript 中 switch case 等于 (== )还是 恒等于(===)? 可以测试一下以下代码,这个 case 中是 等于(==)还是恒等于(===) <script> ...

  4. python技巧 switch case语句

    不同于C语言和SHELL,python中没有switch case语句,关于为什么没有,官方的解释是这样的 使用Python模拟实现的方法: def switch_if(fun, x, y):    ...

  5. asp.net ashx处理程序中switch case的替代方案总结

    目录 1.用委托字典代替switch...case; 2.利用反射替代switch...case: 3.比较两种方案 4.其他方案 4.说明 5.参考 在开发 asp.net 项目中,通常使用一般处理 ...

  6. Python中Swithch Case语法实现

    而python本身没有switch语句,解决方法有以下3种:A.使用dictionaryvalues = { value1: do_some_stuff1, value2: do_some_stuff ...

  7. js中switch/case分支的值可以是变量或表达式

    在一些高级语言如C#中,switch分支的值只能是常量,而js中可以是变量或表达式: <!DOCTYPE html> <html lang="en"> &l ...

  8. thymeleaf中switch case多出一个空行

    以下是<thymeleaf3.0.5中文参考手册.pdf>中的代码,官方代码没有具体去查询. <div th:switch="${user.role}"> ...

  9. C# 中Switch case 返回不止用break

    Switch(temp) { case "A": //跳出循环 break; case "B": //返回值 return var; case "C& ...

随机推荐

  1. erc721-165学习

    ERC165: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md 就是一种发布并能检测到一个智能合约实现了什么接口的标准 这么做 ...

  2. metamask源码学习-controller-transaction

    ()metamask-extension/app/scripts/controllers/transactions Transaction Controller is an aggregate of ...

  3. solidity-library

    library 1)直接使用使用库合约的合约,可以将库合约视为隐式的父合约(base contracts),当然它们不会显式的出现在继承关系中.意思就是不用写is来继承,直接可以在合约中使用: lib ...

  4. WebSocket原理与实践(四)--生成数据帧

    WebSocket原理与实践(四)--生成数据帧 从服务器发往客户端的数据也是同样的数据帧,但是从服务器发送到客户端的数据帧不需要掩码的.我们自己需要去生成数据帧,解析数据帧的时候我们需要分片. 消息 ...

  5. 【Codeforces 331D3】Escaping on Beaveractor

    题意:给\(b\times b\)的网格,其中有\(n\)个不交叉的箭头. 现在有\(q\)个询问,每个询问包含一个点\((x,y)\),以及一个方向\(dir\).时间\(t\). 要求从\((x, ...

  6. 【Codeforces 152E】Garden

    Codeforces 152 E 题意:给你一个\(n\times m\)的格子,每个格子里面有一个值\(a_{i,j}\)表示如果要将这个格子变成路的话需要花费这么多代价.现在有\(k\)个特殊格子 ...

  7. 18-(基础入门篇)GPRS(Air202)拨打电话--(由于板子做修订,所以暂停更新)

    https://www.cnblogs.com/yangfengwu/p/9968883.html 这个直接用官方给的demo就可以 先睹为快 现在说个需求哈,是当初一个人给提出的需求 例如存入的号码 ...

  8. 13-(基础入门篇)系统教程演示(GPRS模块)

    https://www.cnblogs.com/yangfengwu/p/9966702.html 前几节作为基础教程和系统教程的开端,有了前面的基础才更好的学习基础教程和系统教程. https:// ...

  9. [05] Bean的作用域和生命周期

    1.Bean的作用域和初始化时间 之前我们稍微提到过,Spring中管理的Bean,默认都是单例模式,这意味着你多次获取某个对象,得到的都是相同的对象.单例作用域的显性写法是scope属性,如下,这和 ...

  10. LOJ2803 CCC2018 平衡树 数论分块、记忆化搜索

    传送门 题意差评,其实就是一个递推式:\(f_1 = 1 , f_i = \sum\limits_{j=2}^i f_{\lfloor \frac{i}{j} \rfloor}\),然后求\(f_N\ ...