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.
首先,我想为糟糕的头衔道歉,但这是我能做的最好的.我试图拍摄很多截图,希望能让它更容易理解.
所以我正在研究一个不和谐的聊天机器人,现在正在开发一个可以作为待办事项清单的功能.我有一个命令将任务添加到列表中,它们存储在dict中.但是我的问题是以更易读的格式返回列表(见图片).
def show_todo():
for key, value in cal.items():
print(value[0], key)
Run Code Online (Sandbox Code Playgroud)
任务存储在dict被调用的中cal.但是为了让机器人实际发送消息,我需要使用return语句,否则它只是将它打印到控制台而不是实际的聊天(见图片).
def show_todo():
for key, value in cal.items():
return(value[0], key)
Run Code Online (Sandbox Code Playgroud)
以下是我尝试修复它的方法,但由于我使用了返回,for循环无法正常工作.
那么我该如何解决这个问题呢?如何使用return语句将其打印到聊天而不是控制台?
请参阅图片以便更好地理解
我知道这是不可能的。返回将退出它。有没有办法使之成为可能。我有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 ×3
python-3.x ×2
coroutine ×1
for-loop ×1
function ×1
generator ×1
iterator ×1
return ×1
while-loop ×1
yield ×1