switch的python实现

本文首发于知乎

我们知道,python是没有switch语句的,所以当我们要实现这样结构的逻辑时:

var index = 10

switch index {
   case 100  :
      print( "index 的值为 100")
   case 10,15  :
      print( "index 的值为 10 或 15")
   case 5  :
      print( "index 的值为 5")
   default :
      print( "默认 case")
}
复制代码

经常需要用多个if-else来实现。除此之外,我们还可以考虑用字典对应提取的方式来实现,下面我们给出四种实现switch的方法,并对比这四种方法的运行时间

something = 'something'

# 第一种,多次使用if-else结构
if something == 'this':
    the_thing = 1
elif something == 'that':
    the_thing = 2
elif something == 'there':
    the_thing = 3
else:
    the_thing = 4
    
# 第二种,用get设置默认值的字典提取
options = {'this': 1, 'that': 2, 'there': 3}
the_thing = options.get(something, 4)

# 第三种,用if-else配合不设置默认值的字典提取
options = {'this': 1, 'that': 2, 'there': 3}
if something in options:
    the_thing = options[something]
else:
    the_thing = 4
    
# 第四种,用collections模块设置默认值进行字典提取
from collections import defaultdict
default_options = defaultdict(lambda: 4, {'this': 1, 'that': 2, 'there': 3})
the_thing = default_options[something]
复制代码

下面我们对比一下这几种方式提取的速度,分成两种情况

  • 判断的内容在字典中
  • 判断的内容不在字典中

在ifelse.py文件中输入如下内容

import time
from collections import defaultdict

# 计算运行时间的装饰器
def run_time(func):
    def wrapper(*args, **kw):
        start = time.time()
        func(*args, **kw)
        end = time.time()
        print('running', end-start, 's')
    return wrapper

# 准备好两个字典
options = {'this': 1, 'that': 2, 'there': 3}
default_options = defaultdict(lambda: 4, {'this': 1, 'that': 2, 'there': 3})


# 四种方法都定义成函数
# 接受参数something即待判断值
# 每次循环10000000次
@run_time
def first(something):
    for i in range(10000000):
        if something == 'this':
            the_thing = 1
        elif something == 'that':
            the_thing = 2
        elif something == 'there':
            the_thing = 3
        else:
            the_thing = 4

@run_time
def second(something):
    for i in range(10000000):
        the_thing = options.get(something, 4)


@run_time
def third(something):
    for i in range(10000000):
        if something in options:
            the_thing = options[something]
        else:
            the_thing = 4

@run_time
def forth(something):
    for i in range(10000000):
        the_thing = default_options[something]

# 调用函数
if __name__ == '__main__':
	# 判断的内容不在字典中
	first('something')
	second('something')
	third('something')
	forth('something')
	print('-'*20)
	# 判断的内容在字典中
	first('this')
	second('this')
	third('this')
	forth('this')
复制代码

在命令行多次运行

python ifelse.py
复制代码

得到结果如下

-------------第一次---------------
running 1.8487958908081055 s
running 1.63755202293396 s
running 0.7807505130767822 s
running 0.6786513328552246 s
--------------------
running 0.7807483673095703 s
running 2.075996160507202 s
running 1.0349910259246826 s
running 0.740731954574585 s

-------------第二次---------------

running 1.7757258415222168 s
running 1.6395549774169922 s
running 0.8408102989196777 s
running 0.7977871894836426 s
--------------------
running 0.710662841796875 s
running 1.9098539352416992 s
running 1.042982578277588 s
running 0.8197875022888184 s

-------------第三次---------------

running 1.5885050296783447 s
running 1.8237719535827637 s
running 0.9819226264953613 s
running 0.78375244140625 s
--------------------
running 0.6226155757904053 s
running 1.634549617767334 s
running 0.947911262512207 s
running 0.6586313247680664 s
复制代码

从结果中可以看出 1.四种方法之间的对比,后两种方法明显比前两种方法快,且最后一种方法总是最快的。 2.待判断内容是否在字典中设置的对比

  • 第一种全程if-else判断的情况下,早判断出来程序就会早结束,所以if-else判断的内容顺序是有讲究的
  • 而从字典里提取则没有看出显著的不同

由于使用collections模块中的defaultdict虽然最快,但是会占用较多内存,所以最推荐的是第三种方法,使用if-else配合无默认字典提取方法。

参考stackoverflow上的这篇回答

欢迎关注我的知乎专栏

专栏主页:python编程

专栏目录:目录

版本说明:软件及包版本说明

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值