博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python中if elif语句优化_python – 最有效的方式做一个if-elif-elif-else语句当else做的最多?...
阅读量:4475 次
发布时间:2019-06-08

本文共 986 字,大约阅读时间需要 3 分钟。

代码…

options.get(something, doThisMostOfTheTime)()

…看起来它应该更快,但它实际上比if … elif … else构造,因为它必须调用一个函数,这可能是一个严重的性能开销在一个紧的循环。

考虑这些例子…

1.py

something = 'something'

for i in xrange(1000000):

if something == 'this':

the_thing = 1

elif something == 'that':

the_thing = 2

elif something == 'there':

the_thing = 3

else:

the_thing = 4

2.py

something = 'something'

options = {'this': 1, 'that': 2, 'there': 3}

for i in xrange(1000000):

the_thing = options.get(something, 4)

3.py

something = 'something'

options = {'this': 1, 'that': 2, 'there': 3}

for i in xrange(1000000):

if something in options:

the_thing = options[something]

else:

the_thing = 4

4.py

from collections import defaultdict

something = 'something'

options = defaultdict(lambda: 4, {'this': 1, 'that': 2, 'there': 3})

for i in xrange(1000000):

the_thing = options[something]

…并记下它们使用的CPU时间量…

1.py: 160ms

2.py: 170ms

3.py: 110ms

4.py: 100ms

…使用用户时间从time(1)。

选项#4确实有额外的内存开销,为每个不同的密钥未命中添加一个新的项目,所以如果你期望无限多个不同的密钥未命中,我会选择#3,这仍然是一个重大的改进原始结构。

转载地址:http://dcips.baihongyu.com/

你可能感兴趣的文章
软工之404 Note Found团队
查看>>
关于事件冒泡和浏览器默认行为
查看>>
自动测试框架PyUnit
查看>>
SVN使用—概念及生命周期
查看>>
Solr与Lucene的区别
查看>>
js设计模式--方法的链式调用及回调
查看>>
源代码与二进制异同
查看>>
OAuth 白话简明教程 2.授权码模式(Authorization Code)
查看>>
basler 相机拍照简单类综合Emgu.CV---得到图档--原创
查看>>
启动时有两个win7怎么删除一个
查看>>
Linux计划任务crontab
查看>>
《BI那点儿事》数据流转换——模糊分组转换
查看>>
索引学习 查找 数据结构 梳理
查看>>
阿里社招-1
查看>>
大量数据导入到服务器
查看>>
22.文本框验证和外部url的调用
查看>>
2017-2018-1 20155226 《信息安全系统设计基础》第四周学习总结
查看>>
方法(参数的传递)
查看>>
Vue Baidu Map 插件的使用
查看>>
再一次写爬虫 - 爬取猫眼电影 Top100 榜
查看>>