在Python中使用“continue”语句的示例?

问题描述 投票:156回答:9

definition声明的continue是:

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

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

有人会建议一些简单的情况需要continue吗?

python continue
9个回答
198
投票

这是一个简单的例子:

for letter in 'Django':    
    if letter == 'D':
        continue
    printf("Current Letter: {letter}")

输出将是:

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

它继续循环的下一次迭代。


96
投票

我喜欢在循环中继续使用循环,在你开始“开展业务”之前有很多条件需要实现。所以代替这样的代码:

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()

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


17
投票

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

我并不认为这是必要的,因为你总是可以使用if语句来提供相同的逻辑,但是提高代码的可读性可能会有用。


12
投票
import random  

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

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


9
投票

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

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

if precondition_fails(message): continue

''' main code here '''

请注意,您可以在编写主代码后执行此操作,而无需更改代码。如果您对代码进行区分,则只会添加带有“continue”的行,因为主代码没有间距更改。

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


5
投票
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']

4
投票

假设我们要打印所有不是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

3
投票

这不是绝对必要的,因为它可以用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声明之后,错误的值没有成功。


2
投票

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

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,解释器将跳过循环。但是使用continueit只会跳过if-elif语句并直接转到循环的下一个项目。

© www.soinside.com 2019 - 2024. All rights reserved.