简体   繁体   English

什么时候应该使用 for 循环或 while 循环?

[英]When should I use a for loop or a while loop?

I am confused about when using a while-loop or for-loop is better?我很困惑什么时候使用 while 循环或 for 循环更好? I am particularly worried about producing optimized answers to coding questions.我特别担心为编码问题提供优化的答案。 I find myself solving problems just to find out a while-loop would've been faster but am confused about what leads people to choose to use it instead of a for-loop, like what criteria should I be looking for?我发现自己解决问题只是为了发现 while 循环会更快,但对导致人们选择使用它而不是 for 循环的原因感到困惑,比如我应该寻找什么标准? Here's an example of a coding question I answered which checks if a string of parentheses is balanced.这是我回答的一个编码问题的例子,它检查一串括号是否平衡。

def parenCheck(str):
    stack = Stack()
    for x in str:
        if x == '(':
            stack.push(x)
        else:
            if stack.isEmpty():
                return False
            else:
                stack.pop()
    return stack.isEmpty()

Here is the answer I saw for it , which I know is faster because it doesnt use a for-loop:这是我看到的答案,我知道它更快,因为它不使用 for 循环:

def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol == "(":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                s.pop()

        index = index + 1

    if balanced and s.isEmpty():
        return True
    else:
        return False

This cannot be decided by your code that while loop worked faster than for loop.这不能由您的代码决定,while 循环比 for 循环工作得更快。 As of your question on when to use while and for loop, it is decided on the basis of whether we know the number of iterations.至于你关于什么时候使用while和for循环的问题,是根据我们是否知道迭代次数来决定的。 If number of iterations is known, for loop is preferred, whereas while loop is preferred when the iterations are indefinite.如果迭代次数已知,则首选 for 循环,而当迭代不确定时,首选 while 循环。

for (int i : mynumber_list)
Iterator it  = mynumber_list.iterator()
while (it.hasNext())

As can be seen from above, for loop is more readable, simple, and easy in traversing.从上面可以看出,for循环更具可读性,更简单,更容易遍历。 Moreover, iterator.hasNext() has a very high probability of entering into an infinite loop而且,iterator.hasNext() 进入死循环的概率非常高

while can also be useful for user choice input questions, like keep executing the program until the user presses any other key except y. while 也可用于用户选择输入问题,例如继续执行程序直到用户按下除 y 之外的任何其他键。 This is difficult to achieve with for loop.这很难用 for 循环实现。

For the same number of iterations, and content, my guess is that a for loop and wihile have practically the same speed.对于相同数量的迭代和内容,我的猜测是for循环和wihile的速度几乎相同。 But I haven't tested that - mostly I answer numpy questions where we try to avoid either loop (preferring iterations in compiled code).但我还没有测试过 - 大多数情况下我会回答numpy问题,我们试图避免任何一个循环(更喜欢编译代码中的迭代)。

Your examples show the basic case where for results in cleaner, if not faster, code:您的示例显示了基本情况,其中for结果更清晰,如果不是更快,代码:

for x in an_iterator:
    <do something>

versus相对

i = 0
while i < len(an_iterator):
     x = an_iterator[x]
     <do something>
     i += 1

If you must have an index as well, you can use:如果您还必须有索引,则可以使用:

 for i, x in enumerate(an_iterator):
      ....

That ability to iterate directly on things like lists and dictionaries was the main neat feature that caught my attention when I first saw Python in the 1990.当我在 1990 年第一次看到 Python 时,直接对列表和字典之类的东西进行迭代的能力是引起我注意的主要简洁特性。

A common subcase of a for loop accumulates values, so common, that Python provides the popular list comprehension , and extended the syntax to generator expressions and dictionary comprehensions. for loop一个常见子案例累积值,如此常见,以至于 Python 提供了流行的list comprehension推导式,并将语法扩展到生成器表达式和字典推导式。

while still has its uses. while仍然有它的用途。 Other languages have do while and do until variants, which attempt to streamline stepping the variable and testing.其他语言有do whiledo until变体,它们试图简化步进变量和测试。 Python has just the one version with separate steps. Python 只有一个带有单独步骤的版本。 The new walrus operator has the potential of cleaning that up:新的walrus操作员有可能清理它:

https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions
while (block := f.read(256)) != '':
    process(block)

while is most useful when the steps aren't regular, or from a well defined iterator.当步骤不规则或来自定义良好的迭代器时, while最有用。 for can break and continue , but otherwise the sequence is fixed (at the start of iteration). for可以breakcontinue ,但否则序列是固定的(在迭代开始时)。

In addition to enumerate , zip lets us iterate on several things at once.除了enumeratezip可以让我们一次迭代几件事。

The convenience of list comprehensions encourages us to decompose a complicated task into a sequence of comprehensions.列表推导式的便利性鼓励我们将复杂的任务分解为推导式序列。 And to make that even more convenient (and faster/memory efficient) Python provides generators and all sort so itertools .并且为了使它更方便(和更快/内存效率更高),Python 提供了生成器和所有排序itertools In Python 3, range and dictionary keys/items/values all became generator like expressions.在 Python 3 中, range和字典keys/items/values都变成了类似表达式的生成器。

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

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