2017-10-12 251 views
0

我當然知道這是不能直接在Python中,在解決方法(僞)在python中裝飾for循環?

Statement decorators

讀,但我仍想找到一種方法,以編程方式打開(和關閉)的循環爲:

for i in range(L[:]): 
    # do stuff 

for i in range(L[0:N])): 
    # estimate how much time it 
    # took to run the loop over a subset N element of the list 
for i in range(L): 
    # do stuff on the full list 

有任何Python的方式這樣做呢?

+0

你想如何「打開或關閉」這個功能嗎?在我看來,最簡單的方法是將'N'設爲默認爲'None'的可選參數。 – jdehesa

+2

什麼是L?它似乎是你的一個例子中的整數,另一個例子中的一些迭代類型。而當''L [0:N]''是一個序列時,''range(L [0:N])''沒有意義。 – allo

+0

爲什麼不把for循環放入一個函數中,你可以用它作爲裝飾器?它需要成爲裝飾者嗎? – Dschoni

回答

1

假設L是一個列表

import time 

def timed_loop(L,subset,timeout): 
    start = time.time() 
    for i in L[0:subset]: 
     do_something() 
    stop = time.time() 
    if stop-start < timeout: 
     for i in L: 
      do_something_else() 
+0

不錯。如果L也是一個通用迭代器,它會起作用嗎? – ErroriSalvo

+0

只要你能索引L,我會這麼說。 – Dschoni

+0

使其更快:不要重做L [0:子集],但繼續L [subset:] – Dschoni