[英]python loop to run only once for temporary testing
I have a python for loop that iterates over a dictionary. 我有一个迭代字典的python for循环。 The dictionary is very large.
字典很大。 For debugging I want to modify the for loop to run only once.
对于调试,我想将for循环修改为仅运行一次。 How can I limit the for loop to exit after running once.
我如何限制for循环运行一次后退出。
for key in dic:
do_some_stuff()
#after the first iteration exit
In java I can modify the for loop in this way: 在Java中,我可以通过以下方式修改for循环:
for (int i = 0; i < n; i++)
doSomeStuff();
will be limited like this: 这样会受到限制:
for (int i = 0; i < n, i < 1; i++)
doSomeStuff();
It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.
它终止最近的封闭循环,如果循环中有一个,则跳过可选的else子句。
for key in dic:
do_some_stuff()
break
If you want to run the loop for several times (more than once), you can use a counter: 如果要多次(不止一次)运行循环,可以使用一个计数器:
for i, key in enumerate(dic):
do_some_stuff()
if i > 10:
break
This will run the loop for 11 times before break
ing as index (i) begins from 0 and goes till 10 . 这将使循环运行11次,然后
break
因为索引(i)从0开始直到10。
Since you are doing debugging, I would like to recommend you the pdb package: With it, you got much more control over the execution process. 由于您正在进行调试,因此我向您推荐pdb软件包:有了它,您可以更好地控制执行过程。
import pdb
pdb.set_trace()
for key in dic:
do_some_stuff()
You can always slice the dictionary iterator using 您始终可以使用以下方式对字典迭代器进行切片
from itertools import islice
for k in islice(dic, 1):
do_something(k)
Then, to disable it, simply change the 1
to None
. 然后,要禁用它,只需将
1
更改为None
。 Thus you could have a debug flag that decides for you: 因此,您可以使用一个调试标志来决定:
please_debug = True
for k in islice(dic, 1 if please_debug else None):
do_something(k)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.