Consider the following code in C:
for(int i=0; i<10 && some_condition; ++i){
do_something();
}
I would like to write something similar in Python. The best version I can think of is:
i = 0
while some_condition and i<10:
do_something()
i+=1
Frankly, I don't like while
loops that imitate for
loops. This is due to the risk of forgett开发者_运维问答ing to increment the counter variable. Another option, that addressess this risk is:
for i in range(10):
if not some_condition: break
do_something()
Important clarifications
some_condition
is not meant to be calculated during the loop, but rather to specify whether to start the loop in the first placeI'm referring to Python2.6
Which style is preferred? Is there a better idiom to do this?
This might not be related, but there's what I'm used to do... If some_condition
is simple enough, put it in a function and filter
items you iterate over:
def some_condition(element):
return True#False
for i in filter(some_condition, xrange(10)):
pass
You can use this approach also when you iterate over some list of elements.
selected = filter(some_condition, to_process)
for i, item in enumerate(selected):
pass
Again, this might not be your case, you should choose method of filtering items depending on your problem.
In general, the "range
+ break
" style is preferred - but in Python 2.x, use xrange
instead of range
for iteration (this creates the values on-demand instead of actually making a list of numbers).
But it always depends. What's special about the number 10 in this context? What exactly is some_condition
? Etc.
Response to update:
It sounds as though some_condition
is a "loop invariant", i.e. will not change during the loop. In that case, we should just test it first:
if some_condition:
for i in xrange(10):
do_something()
for
loops with a constant upper bound are a bit rare in Python. If you are iterating over somearray
, you might do:
for i in xrange(len(somearray)):
if not some_condition:
break
do_sth_with(i, somearray[i])
or, better:
for i, item in enumerate(somearray):
if not some_condition:
break
do_sth_with(i, item)
精彩评论