yieldPython中关键字的用途是什么?它有什么作用?
例如,我试图理解这段代码1:
def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
Run Code Online (Sandbox Code Playgroud)
这是来电者:
result, candidates = [], [self]
while candidates:
node = candidates.pop()
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
Run Code Online (Sandbox Code Playgroud)
_get_child_candidates调用该方法时会发生什么?列表是否返回?单个元素?它又被召唤了吗?后续通话何时停止?
1.代码来自Jochen Schulz(jrschulz),他为度量空间创建了一个很棒的Python库.这是完整源代码的链接:模块mspace.
我知道这是不可能的。返回将退出它。有没有办法使之成为可能。我有while循环,它计算值。我想从while循环返回该值,并将其用于进一步处理,然后再次返回while循环,并在停止的地方继续。我知道返回会退出循环。如何使其成为可能。
这是示例代码:
import datetime
import time
def fun2(a):
print("count:", a)
def fun():
count = 0
while 1:
count = count+1
time.sleep(1)
print(count)
if count == 5:
return count
a = fun()
fun2(a)
Run Code Online (Sandbox Code Playgroud)
我的输出:
1
2
3
4
5
count: 5
Run Code Online (Sandbox Code Playgroud)
要求的输出:
1
2
3
4
5
count: 5
6
7
8
9
and goes on....
Run Code Online (Sandbox Code Playgroud) python ×2
coroutine ×1
for-loop ×1
generator ×1
iterator ×1
python-3.x ×1
while-loop ×1
yield ×1