Python的Switch语句
2017-04-25 23:30
489 查看
在编程语言中 switch 语句是比较常见的一种语法,但是python却摒弃了switch 官方的建议是使用 if-elif-…-else来代替,但是如果就是想用switch怎么办呢,也有方法
方法一:使用dict字典实现
def switch(arg): sw = {0:"zero",1:"one",3:"three"} # 参数一:要传入的参数arg,参数二:默认值,当dict中没有对应的arg的键值的时候使用该默认值 return sw.get(arg,"nothing") print(switch(8))
方法二:使用lambda表达式实现
switch = {"a":lambda x:x * 2,"b":lambda x:x * 3,"c":lambda x:x ** x} try: # ['x'](y):x表示dict的key,y表示key对应的value的lambda表达式的参数 print(switch["a"](4)) except KeyError as e: pass
创建自己的类来实现
该方法一般不实用,太麻烦。。。# 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
相关文章推荐
- Python学习(13)--Lambda表达式和switch语句的实现
- 在Python中没有switch语句 这个好吗?
- 为什么Python中没有Switch/Case语句?
- python语言没有switch-case语句
- Python没有switch语句的解决方法
- python_3(循环语句、if、switch、for、break、冒泡算法)
- Python为什么没有switch/case语句?
- Python: 没有switch-case语句
- 除了switch,PHP就不能像Python一样使用Map来代替多分枝条件语句吗? (只讨论技术)
- [转载] Python没有switch语句的解决方法
- python 实现switch/case语句
- Python switch/case语句实现方法
- python 基础学习 switch 语句
- python实现switch语句
- python中switch语句用法
- python中没有switch/case语句
- python为何没有switch语句?
- Python学习 之 switch语句
- python字典 switch语句
- python小技巧--用字典映射代替switch case语句