python中if elif语句优化_python – 最有效的方式做一个if-elif-elif-else语句当else做的最多?...
代碼…
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,這仍然是一個重大的改進原始結構。
總結
以上是生活随笔為你收集整理的python中if elif语句优化_python – 最有效的方式做一个if-elif-elif-else语句当else做的最多?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎样开通科创板交易
- 下一篇: python怎么画多重饼状图_Pytho