簡體   English   中英

如何在python中匹配一次后跳過檢查?

[英]How to bypass if checking after matching once in python?

假設我有以下聲明:

for i in range(10000):
  if i==5:
    do_something_for_5()
  else:
    do_something()

所以你可以看到python需要檢查10000次我是否等於5,並且浪費了9999個檢查。 我的問題是,在捕獲5次之后,python是否會繞過if-checking並直接轉到exec do_something()? 有點像整個檢查短路。 怎么做?

更多。

我不認為這是python問題,您經常在許多語言中看到這種檢查模式。(編譯器會對其進行優化嗎?)這種情況僅用於演示,我只是討厭看到計算機進行檢查並檢查無果而已,想知道避免這種情況的技巧。 就像這樣的場景:您知道只有一個壞人,一旦抓住了那個壞人,便撤回警察和安全檢查,讓其他人直接離開,這將使流程運行得更快。

像這樣的更通用的代碼:

for member in member_list:
  if time_consuming_inspect(member)==special_character:#known there is only one candidate match in advance
    do_special_thing(member)
  else:
    do_common_thing(member)

做一個簡單的事情:看到5之后跳出循環,然后運行另一個循環以完成工作:

for i in range(10000):
    if i==5:
        do_something_for_5()
        break
    else:
        do_something()

for i in range(i+1, 10000):
    do_something()

一種方法是改為編寫如下內容:

for i in range(4):
    do_something()

do_something_for_5()

for i in range(6, 10000):
    do_something()

如果不需要按順序執行5的特殊情況,那么這將減少重復:

for i in itertools.chain(range(5), range(6, 10000)):
    print i

聽起來您確實想要像自修改代碼這樣的東西,以便它不再進行檢查,但是我建議您不要這樣做。 進行額外檢查並沒有太大影響。


回應評論

不建議使用以下內容,在此示例中,以下內容有些過時,但確實可以。 成功檢查5后,它將使用其他功能。 請記住,必須查找變量分配給的功能,因此我懷疑速度會提高。 這可能用途非常有限,但是:

do_something = None

def do_something_with_check(i):
    if i != 5:
        print 'Doing something with check.'
    else:
        do_something_for_5()
        global so_something
        do_something = do_something_without_check

def do_something_without_check(i):
    print 'Doing something without check.'

def do_something_for_5():
    print 'Doing something for 5.'

do_something = do_something_with_check

for i in range(10):
    do_something(i)

打印出:

Doing something with check.
Doing something with check.
Doing something with check.
Doing something with check.
Doing something with check.
Doing something for 5.
Doing something without check.
Doing something without check.
Doing something without check.
Doing something without check.
seenFive = False
for i in range(10000):
  if not seenFive and i==5:
    do_something_for_5()
    seenFive = True
  else:
    do_something()

您不能迭代5個以上,並分別執行該功能:

nums = range(10000) # list(range(10000)) on python3
nums.remove(5) # Get rid of 5 from the list.
do_something_for_5()
for i in nums:
    do_something()

我不確定這會有所幫助,因為制作列表的開銷可能比檢查每次迭代中i==5是否多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM