相关疑难解决方法(0)

"yield"关键字有什么作用?

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.

python iterator yield generator coroutine

9664
推荐指数
46
解决办法
212万
查看次数

使用break时在python生成器中的yield语句之后运行代码

我有一个简单的生成器:

def counter(n): 
   counter = 0
   while counter <= n:
      counter += 1
      yield counter
   print(f"Nice! You counted to {counter}")

def test_counter(): 
   for count in counter(6): 
      print(f"count={count}")
      if count > 3: 
         break
Run Code Online (Sandbox Code Playgroud)

在这个例子中,当计数达到 3 时有一个中断。但是代码的唯一问题是中断在 yield 语句终止了生成器的执行。它不会在 yield 语句之后运行 print 语句。有没有办法在发生中断时在 yield 语句之后的生成器中执行代码?

示例运行:

# What happens: 
>>> test_counter()
count=1
count=2
count=3
count=4

# What I'd like to see: 
>>> test_counter()
count=1
count=2
count=3
count=4
Nice! You counted to 4
Run Code Online (Sandbox Code Playgroud)

python generator break

2
推荐指数
2
解决办法
221
查看次数

标签 统计

generator ×2

python ×2

break ×1

coroutine ×1

iterator ×1

yield ×1