日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python中if elif语句优化_python – 最有效的方式做一个if-elif-elif-else语句当else做的最多?...

發布時間:2025/4/5 python 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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做的最多?...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。