Python 中产出关键字的用法是什么? 它能做什么?
例如,我试图理解这个代码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
这就是打电话的人:
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
当方法 _get_child_camedates 被调用时会怎样? 列表是否返回? 单一个元素吗? 是否再次调用? 以后的电话何时停止?
1. 本代码由Jochen Schulz(jrschulz)编写,他为公制空间制作了一个伟大的Python图书馆,与完整的源:模块mspace链接。
生成关键字用于查点/字符,其中函数预期将返回一个输出。我想引用这个非常简单的例A:
# example A
def getNumber():
for r in range(1,10):
return r
以上函数只返回一次, 即使它被多次调用。 现在如果我们以收益率替换返回, 如例B :
# example B
def getNumber():
for r in range(1,10):
yield r
当第一次叫2时,它会返回1,当再次叫2时,3,4,然后它会递增到10。
虽然B的例子在概念上是真实的,但要用Python 3来称呼它,我们必须采取以下行动:
g = getNumber() #instance
print(next(g)) #will print 1
print(next(g)) #will print 2
print(next(g)) #will print 3
# so to assign it to a variables
v = getNumber()
v1 = next(v) #v1 will have 1
v2 = next(v) #v2 will have 2
v3 = next(v) #v3 will have 3
又一个TRL;DR
列表中的迭代器 : 下一个 () 返回列表的下一个元素 。
迭代生成器: 下一个 () 将计算苍蝇上的下一个元素( 执行代码)
您可以通过下拨“无论流量如何复杂”,将产出/生成器视为手动运行外部控制流的一种方式(如继续循环一步),然后调用该输出/生成器作为手动运行外部控制流的一种方式。
注意 : 生成器不是一个正常的函数。 它会像本地变量( stack) 一样记住先前的状态 。 请参看其他答案或文章以详细解释 。 生成器只能重复一次 。 您可以不生产, 但不会是那么好, 所以它可以被视为“ 非常好” 的语言糖 。
收益率和返回一样, 它会返回任何您告诉它的东西( 作为生成器 ) 。 区别在于下次您调用生成器时, 执行从最后一次调用开始到收益语句 。 与返回不同的是, 当收益发生时, 堆叠框架不会被清理, 但是控制会被转回调回调用方, 因此下次调用函数时, 它的状态将会恢复 。
在您的代码中,函数获取_child_camedates 的动作就像一个迭代器,这样当您扩展列表时,它会一次在新列表中添加一个元素 。
列表。extendend calls a plerator until it's fulled it's explator until. 如果是您所贴的代码样本, 只需将图普还给列表, 并附加到列表中, 就会更加清楚 。
- 功能 - 返回。
发电机 -- -- 产量(含有一个或多个产量和零或更多回报率)。
names = ['Sam', 'Sarah', 'Thomas', 'James']
# Using function
def greet(name) :
return f'Hi, my name is {name}.'
for each_name in names:
print(greet(each_name))
# Output:
>>>Hi, my name is Sam.
>>>Hi, my name is Sarah.
>>>Hi, my name is Thomas.
>>>Hi, my name is James.
# using generator
def greetings(names) :
for each_name in names:
yield f'Hi, my name is {each_name}.'
for greet_name in greetings(names):
print (greet_name)
# Output:
>>>Hi, my name is Sam.
>>>Hi, my name is Sarah.
>>>Hi, my name is Thomas.
>>>Hi, my name is James.
发电机看起来像一个函数,但行为举止却像一个迭代器。
发件人继续从它所在的位置执行 。 恢复后, 函数在最后产值运行后立即继续执行 。 这允许它的代码在一段时间内生成一系列的值, 代之以它们一次性计算全部值, 然后把它们像列表一样送回去 。
def function():
yield 1 # return this first
yield 2 # start continue from here (yield don't execute above code once executed)
yield 3 # give this at last (yield don't execute above code once executed)
for processed_data in function():
print(processed_data)
#Output:
>>>1
>>>2
>>>3
注:放弃不应在尝试中.最终建造。