python中if elif语句优化_python – 最有效的方式做一个if-elif-elif-else语句当else做的最多?...
代碼…
options.get(something, doThisMostOfTheTime)()
…看起來(lái)它應(yīng)該更快,但它實(shí)際上比if … elif … else構(gòu)造,因?yàn)樗仨氄{(diào)用一個(gè)函數(shù),這可能是一個(gè)嚴(yán)重的性能開(kāi)銷(xiāo)在一個(gè)緊的循環(huán)。
考慮這些例子…
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時(shí)間量…
1.py: 160ms
2.py: 170ms
3.py: 110ms
4.py: 100ms
…使用用戶(hù)時(shí)間從time(1)。
選項(xiàng)#4確實(shí)有額外的內(nèi)存開(kāi)銷(xiāo),為每個(gè)不同的密鑰未命中添加一個(gè)新的項(xiàng)目,所以如果你期望無(wú)限多個(gè)不同的密鑰未命中,我會(huì)選擇#3,這仍然是一個(gè)重大的改進(jìn)原始結(jié)構(gòu)。
總結(jié)
以上是生活随笔為你收集整理的python中if elif语句优化_python – 最有效的方式做一个if-elif-elif-else语句当else做的最多?...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 怎样开通科创板交易
- 下一篇: python怎么画多重饼状图_Pytho