何为使用yield
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_candidates
是否调用 ? 列表是否返回 ? 单元素 ? 是否又调用 ? 以后的呼叫何时停止 ?
1. 本代码由Jochen Schulz(jrschulz)编写,他为公制空间制作了一个伟大的Python图书馆。模块 m 空间.
这样想吧:
a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a. a.next()
方法。因此,一个产出式的函数最终会变成这样:
原文:
def some_function():
for i in xrange(4):
yield i
for i in some_function():
print i
Python 翻译用上述代码所做的基本上就是:
class it:
def __init__(self):
# Start at -1 so that we get 0 when we add 1 below.
self.count = -1
# The __iter__ method will be called once by the 'for' loop.
# The rest of the magic happens on the object returned by this method.
# In this case it is the object itself.
def __iter__(self):
return self
# The next method will be called repeatedly by the 'for' loop
# until it raises StopIteration.
def next(self):
self.count += 1
if self.count < 4:
return self.count
else:
# A StopIteration exception is raised
# to signal that the iterator is done.
# This is caught implicitly by the 'for' loop.
raise StopIteration
def some_func():
return it()
for i in some_func():
print i
更深入了解幕后发生的事for
循环可以重写到此 :
iterator = some_func()
try:
while 1:
print iterator.next()
except StopIteration:
pass
这更有意义还是更让人困惑?
我应当指出,这一点是a 为说明目的过于简化。 )
在皮顿generators
(一种特殊类型的iterators
)用于产生一系列数值和yield
关键字就和return
生成功能关键字。
另一件有趣的事yield
关键字在保存state
a 发电机功能.
所以,我们可以设定number
每次对一个不同的值generator
产值。
以下是一个例子:
def getPrimes(number):
while True:
if isPrime(number):
number = yield number # a miracle occurs here
number += 1
def printSuccessivePrimes(iterations, base=10):
primeGenerator = getPrimes(base)
primeGenerator.send(None)
for power in range(iterations):
print(primeGenerator.send(base ** power))
就像每个答案都暗示的那样yield
用于创建序列生成器。 它用于动态生成某些序列。 例如, 在网络上逐行读取文件行时, 您可以使用yield
函数如下:
def getNextLines():
while con.isOpen():
yield con.read()
您可在您的代码中使用以下代码:
for line in getNextLines():
doSomeThing(line)
执行控制控制
执行控制将从下拉林( GetNextLines) 转到for
当输出被执行时循环。 因此, 每次引用 NextLines () 时, 执行从上次暂停的点开始 。
因此,简言之,一个函数具有以下代码
def simpleYield():
yield "first time"
yield "second time"
yield "third time"
yield "Now some useful value {}".format(12)
for i in simpleYield():
print i
将打印
"first time"
"second time"
"third time"
"Now some useful value 12"
通常情况下, 它会用来创建一个不起作用的代名词。 将“ ield” 当作您函数的附加件, 以及您作为数组的函数。 如果符合某些标准, 您可以在函数中添加此值, 使之成为代名词 。
arr=[]
if 2>0:
arr.append(2)
def func():
if 2>0:
yield 2
两者的输出结果相同。
使用产量的主要优势是创建迭代器。 迭代器在即时计算时不会计算每个项目的价值。 它们只在您要求时才计算。 这被称为懒惰评价 。
缩略yield
keywit 用于查点/ 字符中, 函数预期将返回一个输出。 我想引用此非常简单 。例例A:
# example A
def getNumber():
for r in range(1,10):
return r
上述函数只返回1即使它被多次调用。 如果我们替换return
与yield
以内例B:
# example B
def getNumber():
for r in range(1,10):
yield r
它会回来的1第一次调用时2当日,3,4直至10岁为止的增量。
尽管《公约》例B在概念上是真实的,但称它为Python 3( 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