简体   繁体   English

循环条件在python中

[英]Loop with conditions in python

Consider the following code in C: 考虑C中的以下代码:

for(int i=0; i<10 && some_condition; ++i){
    do_something();
}

I would like to write something similar in Python. 我想在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. 坦率地说,我不喜欢while模仿循环for循环。 This is due to the risk of forgetting 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 重要的澄清

  1. some_condition is not meant to be calculated during the loop, but rather to specify whether to start the loop in the first place some_condition不是要在循环期间计算,而是指定是否首先启动循环

  2. I'm referring to Python2.6 我指的是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: 这可能没有关系,但是我已经习惯了...如果some_condition足够简单,可以将它放在一个函数中并filter迭代的项目:

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). 通常,首选“ range + break ”样式 - 但在Python 2.x中,使用xrange而不是迭代range (这会按需创建值而不是实际创建数字列表)。

But it always depends. 但它总是取决于。 What's special about the number 10 in this context? 在这种情况下,10号的特殊之处是什么? What exactly is some_condition ? some_condition究竟是some_condition Etc. 等等。

Response to update: 对更新的回应:

It sounds as though some_condition is a "loop invariant", ie will not change during the loop. 听起来好像some_condition是“循环不变”,即在循环期间不会改变。 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. 具有常量上限的for循环在Python中有点罕见。 If you are iterating over somearray , you might do: 如果你迭代somearray ,你可以这样做:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM