switch的python实现

switch的python实现经常需要用多个if-else来实现。除此之外,我们还可以考虑用字典对应提取的方式来实现,下面我们给出四种实现switch的方法,并对比这四种方法的运行时间 1.四种方法之间的对比,后两种方法明显比前两种方法快,且最后一种方法总是最快的。 由于使用collections模块中的d…

本文首发于知乎

我们知道,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编程

专栏目录:目录

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

今天的文章switch的python实现分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:http://bianchenghao.cn/21117.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注