Python 中“continue”语句的示例用法?
- 2025-02-18 09:24:00
- admin 原创
- 75
问题描述:
该语句的定义是continue
:
该
continue
语句继续进行循环的下一次迭代。
我找不到任何好的代码示例。
有人可以提出一些必要的简单案例吗continue
?
解决方案 1:
这是一个简单的例子:
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
:)并继续循环的下一次迭代。
解决方案 2:
我喜欢在循环中使用 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)。
解决方案 3:
通常,continue 是必要/有用的情况是当您想要跳过循环中的剩余代码并继续迭代时。
我并不认为这是必要的,因为你总是可以使用 if 语句来提供相同的逻辑,但它可能有助于提高代码的可读性。
解决方案 4:
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 返回一个整数。为了清楚起见,我省略了它。
解决方案 5:
有些人对可读性做出了评论,说道“哦,它对可读性没有太大的帮助,谁在乎呢?”
假设在主代码之前需要进行检查:
if precondition_fails(message): continue
''' main code here '''
请注意,您可以在编写主代码后执行此操作,而无需对该代码进行任何更改。如果您比较代码,则只有添加的带有“continue”的行会突出显示,因为主代码的间距没有变化。
想象一下,如果您必须对生产代码进行修复,结果发现只需添加一行 continue 即可。当您查看代码时,很容易看出这是唯一的更改。如果您开始将主代码包装在 if/else 中,diff 将突出显示新缩进的代码,除非您忽略间距更改,这在 Python 中尤其危险。我认为,除非您遇到过必须在短时间内推出代码的情况,否则您可能不会完全理解这一点。
解决方案 6:
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']
解决方案 7:
假设我们要打印所有不是 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
解决方案 8:
它不是绝对必要的,因为它可以用 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
。
解决方案 9:
这是关于 continue 和 break 语句的非常好的视觉表示
来源
解决方案 10:
例如,如果您想根据变量的值做不同的事情:
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 语句并直接转到循环的下一个项。
扫码咨询,免费领取项目管理大礼包!