该定义中的continue语句是:
该
continue语句将继续循环的下一次迭代.
我找不到任何好的代码示例.
有人可以建议一些简单的案例continue吗?
Sne*_*mar 205
这是一个简单的例子:
for letter in 'Django':
if letter == 'D':
continue
printf("Current Letter: {letter}")
Run Code Online (Sandbox Code Playgroud)
输出将是:
Current Letter: j
Current Letter: a
Current Letter: n
Current Letter: g
Current Letter: o
Run Code Online (Sandbox Code Playgroud)
它继续循环的下一次迭代:
Lau*_*low 100
我喜欢使用continue in循环,在你开始"开展业务"之前需要完成很多目标.所以代替这样的代码:
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()
Run Code Online (Sandbox Code Playgroud)
我得到这样的代码:
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()
Run Code Online (Sandbox Code Playgroud)
通过这样做,我避免了非常深层嵌套的代码.此外,通过首先消除最常出现的情况很容易优化循环,因此当没有其他showstopper时,我只需要处理不常见但很重要的情况(例如除数为0).
pca*_*cao 17
通常情况下,continue是必要/有用的,当你想跳过循环中的剩余代码并继续迭代时.
我并不认为这是必要的,因为你总是可以使用if语句来提供相同的逻辑,但是提高代码的可读性可能会有用.
小智 12
import random
for i in range(20):
x = random.randint(-5,5)
if x == 0: continue
print 1/x
Run Code Online (Sandbox Code Playgroud)
继续是一个非常重要的控制声明.上面的代码表示典型的应用,其中可以避免除以零的结果.我经常在需要存储程序输出时使用它,但是如果程序崩溃则不想存储输出.注意,为了测试上面的例子,用print 1/float(x)替换最后一个语句,或者只要有一个分数就会得到零,因为randint返回一个整数.为清楚起见,我省略了它.
有些人评论了可读性,并说"哦,这对可读性有多大帮助,谁在乎呢?"
假设您需要在主代码之前进行检查:
if precondition_fails(message): continue
''' main code here '''
Run Code Online (Sandbox Code Playgroud)
请注意,您可以在编写主代码后执行此操作,而无需更改代码.如果您对代码进行区分,则只会添加带有"continue"的行,因为主代码没有间距更改.
想象一下,如果你必须对生产代码进行修复,结果只是添加了一行继续.很容易看出,这是您查看代码时唯一的变化.如果你开始在if/else中包装主代码,diff将突出显示新缩进的代码,除非你忽略间距更改,这在Python中尤其危险.我认为除非您遇到必须在短时间内推出代码的情况,否则您可能不会完全理解这一点.
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']
Run Code Online (Sandbox Code Playgroud)