"continue" 和 "yield" 这对关键字在 Python 中有什么作用?
What does the pair of keywords, "continue" and "yield" do in Python?
当我阅读另一个关于 finding all cycles in graph implementation 的讨论线程时,我遇到了这个问题。谁能解释一下这个例子中这对关键字的用法?谢谢。
01 def dfs(graph, start, end):
02 fringe = [(start, [])]
03 while fringe:
04 state, path = fringe.pop()
05 if path and state == end:
06 yield path
07 continue
08 for next_state in graph[state]:
09 if next_state in path:
10 continue
11 fringe.append((next_state, path+[next_state]))
>>> graph = { 1: [2, 3, 5], 2: [1], 3: [1], 4: [2], 5: [2] }
>>> cycles = [[node]+path for node in graph for path in dfs(graph, node, node)]
>>> len(cycles)
7
>>> cycles
[[1, 5, 2, 1], [1, 3, 1], [1, 2, 1], [2, 1, 5, 2], [2, 1, 2], [3, 1, 3], [5, 2, 1, 5]]
这两个关键字没有密切相关。
continue
关键字只能出现在循环体中(for
或 while
语句),并导致控制流向 return循环的顶部而不是继续循环体的其余部分。它通常是在 if
或 else
块中缩进整个循环体的替代方法。这个:
while foo():
if something():
continue
bar()
baz()
完全等同于:
while foo():
if not something():
bar()
baz() # but note that these lines are more indented in this version!
另一个与continue
密切相关的关键字是break
,它会导致控制流立即退出循环,而不是回到顶部。 continue
和 break
都只能影响最近的循环,所以如果你有嵌套的控制结构,可能很难一次打破它们(或者 continue
来自在一个内部的里面)。
yield
关键字非常不同。尽管它经常出现在循环中,但并非必须如此。相反,它只允许在函数体内使用。它将函数更改为 "generator function"。当一个生成器函数被调用时,它的代码不会立即 运行,而是创建一个 "generator object" 并 returned 给调用者。生成器对象是一种迭代器,可以通过 for
循环(或手动调用 next()
对其进行迭代)。只有当生成器对象被迭代时,函数的代码才会运行。每次到达 yield
语句时,函数的执行暂停,产生的值(或 None
如果未指定值)将作为迭代值给出。 (请注意,当有人随意称呼某物为 "generator" 时,他们的意思可能是生成器函数或生成器对象。从上下文中通常可以清楚地知道他们的意思。)
下面是一些使用生成器打印 1
、2
和 3
的示例代码:
def generator_function():
yield 1 # because it contains `yield` statements, this is a generator function
yield 2
yield 3
generator_object = generator_function() # you can create a variable for the generator object
for value in generator_object: # but often you'd create it on the same line as the loop
print(value)
另一个有点类似于yield
的关键字是return
,它也只在函数中才有意义。它立即结束函数的执行到 return 指定的值(或 None
如果没有指定值)。
您显示的 dfs
函数先后使用了 yield
和 continue
。它所做的是首先产生一个值(停止生成器函数的执行,直到请求下一个值),然后一旦恢复执行,它就会回到循环的开始。
如果您愿意,可以重写该函数以避免其中任何一个(尽管生成的函数的工作方式会有所不同,因为它不再是惰性生成器):
def dfs(graph, start, end):
results = [] # maintain a list of results to avoid yielding
fringe = [(start, [])]
while fringe:
state, path = fringe.pop()
if path and state == end:
results.add(path) # don't yield any more, just add the path to the results list
else: # add an else block instead of using continue
for next_state in graph[state]:
if next_state not in path: # reverse the condition instead of continue
fringe.append((next_state, path+[next_state]))
return results # return the results at the end of the function
我注意到函数的生成器版本在大多数情况下可能更好。使用 continue
而不是更多缩进更像是一种样式选择,并且对代码的逻辑或性能没有太大影响(只是它的外观)。
当我阅读另一个关于 finding all cycles in graph implementation 的讨论线程时,我遇到了这个问题。谁能解释一下这个例子中这对关键字的用法?谢谢。
01 def dfs(graph, start, end):
02 fringe = [(start, [])]
03 while fringe:
04 state, path = fringe.pop()
05 if path and state == end:
06 yield path
07 continue
08 for next_state in graph[state]:
09 if next_state in path:
10 continue
11 fringe.append((next_state, path+[next_state]))
>>> graph = { 1: [2, 3, 5], 2: [1], 3: [1], 4: [2], 5: [2] }
>>> cycles = [[node]+path for node in graph for path in dfs(graph, node, node)]
>>> len(cycles)
7
>>> cycles
[[1, 5, 2, 1], [1, 3, 1], [1, 2, 1], [2, 1, 5, 2], [2, 1, 2], [3, 1, 3], [5, 2, 1, 5]]
这两个关键字没有密切相关。
continue
关键字只能出现在循环体中(for
或 while
语句),并导致控制流向 return循环的顶部而不是继续循环体的其余部分。它通常是在 if
或 else
块中缩进整个循环体的替代方法。这个:
while foo():
if something():
continue
bar()
baz()
完全等同于:
while foo():
if not something():
bar()
baz() # but note that these lines are more indented in this version!
另一个与continue
密切相关的关键字是break
,它会导致控制流立即退出循环,而不是回到顶部。 continue
和 break
都只能影响最近的循环,所以如果你有嵌套的控制结构,可能很难一次打破它们(或者 continue
来自在一个内部的里面)。
yield
关键字非常不同。尽管它经常出现在循环中,但并非必须如此。相反,它只允许在函数体内使用。它将函数更改为 "generator function"。当一个生成器函数被调用时,它的代码不会立即 运行,而是创建一个 "generator object" 并 returned 给调用者。生成器对象是一种迭代器,可以通过 for
循环(或手动调用 next()
对其进行迭代)。只有当生成器对象被迭代时,函数的代码才会运行。每次到达 yield
语句时,函数的执行暂停,产生的值(或 None
如果未指定值)将作为迭代值给出。 (请注意,当有人随意称呼某物为 "generator" 时,他们的意思可能是生成器函数或生成器对象。从上下文中通常可以清楚地知道他们的意思。)
下面是一些使用生成器打印 1
、2
和 3
的示例代码:
def generator_function():
yield 1 # because it contains `yield` statements, this is a generator function
yield 2
yield 3
generator_object = generator_function() # you can create a variable for the generator object
for value in generator_object: # but often you'd create it on the same line as the loop
print(value)
另一个有点类似于yield
的关键字是return
,它也只在函数中才有意义。它立即结束函数的执行到 return 指定的值(或 None
如果没有指定值)。
您显示的 dfs
函数先后使用了 yield
和 continue
。它所做的是首先产生一个值(停止生成器函数的执行,直到请求下一个值),然后一旦恢复执行,它就会回到循环的开始。
如果您愿意,可以重写该函数以避免其中任何一个(尽管生成的函数的工作方式会有所不同,因为它不再是惰性生成器):
def dfs(graph, start, end):
results = [] # maintain a list of results to avoid yielding
fringe = [(start, [])]
while fringe:
state, path = fringe.pop()
if path and state == end:
results.add(path) # don't yield any more, just add the path to the results list
else: # add an else block instead of using continue
for next_state in graph[state]:
if next_state not in path: # reverse the condition instead of continue
fringe.append((next_state, path+[next_state]))
return results # return the results at the end of the function
我注意到函数的生成器版本在大多数情况下可能更好。使用 continue
而不是更多缩进更像是一种样式选择,并且对代码的逻辑或性能没有太大影响(只是它的外观)。