“继续”的使用示例Python 中的语句?

发布于 2024-12-19 19:41:36 字数 288 浏览 5 评论 0原文

continue 语句的定义是:

continue 语句继续执行循环的下一次迭代。

我找不到任何好的代码示例。

有人可以建议一些需要继续的简单情况吗?

The definition of the continue statement is:

The continue statement continues with the next iteration of the loop.

I can't find any good examples of code.

Could someone suggest some simple cases where continue is necessary?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

胡大本事 2024-12-26 19:41:39

例如,如果您想根据变量的值执行不同的操作:

my_var = 1
for items in range(0,100):
    if my_var < 10:
        continue
    elif my_var == 10:
        print("hit")
    elif my_var > 10:
        print("passed")
    my_var = my_var + 1

在上面的示例中,如果我使用 break 解释器将跳过循环。但使用 continue 它只会跳过 if-elif 语句并直接进入循环的下一项。

For example if you want to do diferent things depending on the value of a variable:

my_var = 1
for items in range(0,100):
    if my_var < 10:
        continue
    elif my_var == 10:
        print("hit")
    elif my_var > 10:
        print("passed")
    my_var = my_var + 1

In the example above if I use break the interpreter will skip the loop. But with continueit only skips the if-elif statements and go directly to the next item of the loop.

你的呼吸 2024-12-26 19:41:38
import random  

for i in range(20):  
    x = random.randint(-5,5)  
    if x == 0: continue  
    print 1/x  

continue 是一个极其重要的控制语句。上面的代码表示一个典型的应用,可以避免除以零的结果。当我需要存储程序的输出,但又不想在程序崩溃时存储输出时,我经常使用它。请注意,要测试上面的示例,请将最后一个语句替换为 print 1/float(x),否则只要有分数,就会得到零,因为 randint 返回一个整数。为了清楚起见,我省略了它。

import random  

for i in range(20):  
    x = random.randint(-5,5)  
    if x == 0: continue  
    print 1/x  

continue is an extremely important control statement. The above code indicates a typical application, where the result of a division by zero can be avoided. I use it often when I need to store the output from programs, but dont want to store the output if the program has crashed. Note, to test the above example, replace the last statement with print 1/float(x), or you'll get zeros whenever there's a fraction, since randint returns an integer. I omitted it for clarity.

<逆流佳人身旁 2024-12-26 19:41:38

有些人对可读性发表了评论,说“哦,这对可读性没有多大帮助,谁在乎呢?”

假设您需要在主代码之前进行检查:

if precondition_fails(message): continue

''' main code here '''

请注意,您可以在编写主代码之后执行此操作,而无需以任何方式更改该代码。如果您比较代码,则只有添加的带有“继续”的行才会突出显示,因为主代码没有间距更改。

想象一下,如果您必须对生产代码进行修复,结果只是添加一行带有 continue 的代码。当您查看代码时,很容易看出这是唯一的更改。如果您开始将主代码包装在 if/else 中,diff 将突出显示新缩进的代码,除非您忽略间距更改,这在 Python 中尤其危险。我认为除非您遇到过必须在短时间内推出代码的情况,否则您可能不会完全理解这一点。

Some people have commented about readability, saying "Oh it doesn't help readability that much, who cares?"

Suppose you need a check before the main code:

if precondition_fails(message): continue

''' main code here '''

Note you can do this after the main code was written without changing that code in anyway. If you diff the code, only the added line with "continue" will be highlighted since there are no spacing changes to the main code.

Imagine if you have to do a breakfix of production code, which turns out to simply be adding a line with continue. It's easy to see that's the only change when you review the code. If you start wrapping the main code in if/else, diff will highlight the newly indented code, unless you ignore spacing changes, which is dangerous particularly in Python. I think unless you've been in the situation where you have to roll out code on short notice, you might not fully appreciate this.

冷血 2024-12-26 19:41:38
def filter_out_colors(elements):
  colors = ['red', 'green']
  result = []
  for element in elements:
    if element in colors:
       continue # skip the element
    # You can do whatever here
    result.append(element)
  return result

  >>> filter_out_colors(['lemon', 'orange', 'red', 'pear'])
  ['lemon', 'orange', 'pear']
def filter_out_colors(elements):
  colors = ['red', 'green']
  result = []
  for element in elements:
    if element in colors:
       continue # skip the element
    # You can do whatever here
    result.append(element)
  return result

  >>> filter_out_colors(['lemon', 'orange', 'red', 'pear'])
  ['lemon', 'orange', 'pear']
雪若未夕 2024-12-26 19:41:38

假设我们要打印所有不是 3 和 5 的倍数的数字

for x in range(0, 101):
    if x % 3 ==0 or x % 5 == 0:
        continue
        #no more code is executed, we go to the next number 
    print x

Let's say we want to print all numbers which are not multiples of 3 and 5

for x in range(0, 101):
    if x % 3 ==0 or x % 5 == 0:
        continue
        #no more code is executed, we go to the next number 
    print x
守护在此方 2024-12-26 19:41:38

这并不是绝对必要的,因为它可以使用 IF 来完成,但它更具可读性,并且在运行时成本也更低。

我使用它是为了在数据不满足某些要求时跳过循环中的迭代:

# List of times at which git commits were done.
# Formatted in hour, minutes in tuples.
# Note the last one has some fantasy.
commit_times = [(8,20), (9,30), (11, 45), (15, 50), (17, 45), (27, 132)]

for time in commit_times:
    hour = time[0]
    minutes = time[1]

    # If the hour is not between 0 and 24
    # and the minutes not between 0 and 59 then we know something is wrong.
    # Then we don't want to use this value,
    # we skip directly to the next iteration in the loop.
    if not (0 <= hour <= 24 and 0 <= minutes <= 59):
        continue

    # From here you know the time format in the tuples is reliable.
    # Apply some logic based on time.
    print("Someone commited at {h}:{m}".format(h=hour, m=minutes))

输出:

Someone commited at 8:20
Someone commited at 9:30
Someone commited at 11:45
Someone commited at 15:50
Someone commited at 17:45

如您所见,错误的值在 continue 语句之后没有出现。

It is not absolutely necessary since it can be done with IFs but it's more readable and also less expensive in run time.

I use it in order to skip an iteration in a loop if the data does not meet some requirements:

# List of times at which git commits were done.
# Formatted in hour, minutes in tuples.
# Note the last one has some fantasy.
commit_times = [(8,20), (9,30), (11, 45), (15, 50), (17, 45), (27, 132)]

for time in commit_times:
    hour = time[0]
    minutes = time[1]

    # If the hour is not between 0 and 24
    # and the minutes not between 0 and 59 then we know something is wrong.
    # Then we don't want to use this value,
    # we skip directly to the next iteration in the loop.
    if not (0 <= hour <= 24 and 0 <= minutes <= 59):
        continue

    # From here you know the time format in the tuples is reliable.
    # Apply some logic based on time.
    print("Someone commited at {h}:{m}".format(h=hour, m=minutes))

Output:

Someone commited at 8:20
Someone commited at 9:30
Someone commited at 11:45
Someone commited at 15:50
Someone commited at 17:45

As you can see, the wrong value did not make it after the continue statement.

逐鹿 2024-12-26 19:41:38

这是关于 continue 和 break 语句的非常好的视觉表示

继续示例

来源

Here is a very good visual representation about continue and break statements

Continue example

source

GRAY°灰色天空 2024-12-26 19:41:37

这是一个简单的示例:

for letter in 'Django':    
    if letter == 'D':
        continue
    print("Current Letter: " + letter)

输出将是:

Current Letter: j
Current Letter: a
Current Letter: n
Current Letter: g
Current Letter: o

它跳过当前迭代的其余部分(此处:print)并继续循环的下一个迭代。

Here's a simple example:

for letter in 'Django':    
    if letter == 'D':
        continue
    print("Current Letter: " + letter)

Output will be:

Current Letter: j
Current Letter: a
Current Letter: n
Current Letter: g
Current Letter: o

It skips the rest of the current iteration (here: print) and continues to the next iteration of the loop.

执着的年纪 2024-12-26 19:41:37

我喜欢在循环中使用 continue,在“开始做正事”之前需要满足很多条件。因此,不是这样的代码:

for x, y in zip(a, b):
    if x > y:
        z = calculate_z(x, y)
        if y - z < x:
            y = min(y, z)
            if x ** 2 - y ** 2 > 0:
                lots()
                of()
                code()
                here()

我得到这样的代码:

for x, y in zip(a, b):
    if x <= y:
        continue
    z = calculate_z(x, y)
    if y - z >= x:
        continue
    y = min(y, z)
    if x ** 2 - y ** 2 <= 0:
        continue
    lots()
    of()
    code()
    here()

通过这样做,我避免了非常深的嵌套代码。此外,通过首先消除最常出现的情况来优化循环很容易,这样当没有其他阻碍时,我只需处理不常见但重要的情况(例如除数为 0)。

I like to use continue in loops where there are a lot of contitions to be fulfilled before you get "down to business". So instead of code like this:

for x, y in zip(a, b):
    if x > y:
        z = calculate_z(x, y)
        if y - z < x:
            y = min(y, z)
            if x ** 2 - y ** 2 > 0:
                lots()
                of()
                code()
                here()

I get code like this:

for x, y in zip(a, b):
    if x <= y:
        continue
    z = calculate_z(x, y)
    if y - z >= x:
        continue
    y = min(y, z)
    if x ** 2 - y ** 2 <= 0:
        continue
    lots()
    of()
    code()
    here()

By doing it this way I avoid very deeply nested code. Also, it is easy to optimize the loop by eliminating the most frequently occurring cases first, so that I only have to deal with the infrequent but important cases (e.g. divisor is 0) when there is no other showstopper.

遥远的绿洲 2024-12-26 19:41:37

通常, continue 是必要/有用的情况是当您想要跳过循环中的剩余代码并继续迭代时。

我真的不认为这是必要的,因为您始终可以使用 if 语句来提供相同的逻辑,但它可能有助于提高代码的可读性。

Usually the situation where continue is necessary/useful, is when you want to skip the remaining code in the loop and continue iteration.

I don't really believe it's necessary, since you can always use if statements to provide the same logic, but it might be useful to increase readability of code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文