2017-10-12 126 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