yieldPython中的关键字有什么用?它有什么作用?
yield
例如,我试图理解这个代码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调用方法时会发生什么?是否返回列表?单个元素?又叫了吗?后续呼叫何时停止?
_get_child_candidates
要了解yield它的作用,您必须了解生成器是什么。在了解生成器之前,您必须了解iterables。
创建列表时,您可以一项一项地阅读其项目。一项一项地读取它的项目称为迭代:
>>> mylist = [1, 2, 3] >>> for i in mylist: ... print(i) 1 2 3
mylist是一个可迭代的。当您使用列表推导式时,您创建了一个列表,因此是一个可迭代对象:
mylist
>>> mylist = [x*x for x in range(3)] >>> for i in mylist: ... print(i) 0 1 4
您可以使用“ for... in...”的所有内容都是可迭代的;lists, strings, 文件…
for... in...
lists
strings
这些可迭代对象很方便,因为您可以随心所欲地读取它们,但是您将所有值存储在内存中,当您有很多值时,这并不总是您想要的。
生成器是迭代器,一种只能迭代一次的可迭代对象。生成器不会将所有值存储在内存中,它们会即时生成值:
>>> mygenerator = (x*x for x in range(3)) >>> for i in mygenerator: ... print(i) 0 1 4
除了您使用()而不是[]. 但是,您不能执行for i in mygenerator第二次,因为生成器只能使用一次:它们计算 0,然后忘记它并计算 1,然后一一计算 4。
()
[]
for i in mygenerator
yield是一个像 一样使用的关键字return,除了该函数将返回一个生成器。
return
>>> def create_generator(): ... mylist = range(3) ... for i in mylist: ... yield i*i ... >>> mygenerator = create_generator() # create a generator >>> print(mygenerator) # mygenerator is an object! <generator object create_generator at 0xb7555c34> >>> for i in mygenerator: ... print(i) 0 1 4
这是一个无用的示例,但是当您知道您的函数将返回大量您只需要读取一次的值时,它会很方便。
要掌握yield,你必须明白,当你调用函数时,你写在函数体中的代码并没有运行。该函数只返回生成器对象,这有点棘手。
然后,您的代码将在每次for使用生成器时从停止的地方继续。
for
现在是困难的部分:
第一次for调用从您的函数创建的生成器对象时,它将从头运行您的函数中的代码,直到命中yield,然后它将返回循环的第一个值。然后,每个后续调用将运行您在函数中编写的循环的另一次迭代并返回下一个值。这将一直持续到生成器被认为是空的,当函数运行时没有点击 ,就会发生这种情况yield。这可能是因为循环已经结束,或者因为您不再满足"if/else".
"if/else"
Generator:
# Here you create the method of the node object that will return the generator def _get_child_candidates(self, distance, min_dist, max_dist): # Here is the code that will be called each time you use the generator object: # If there is still a child of the node object on its left # AND if the distance is ok, return the next child if self._leftchild and distance - max_dist < self._median: yield self._leftchild # If there is still a child of the node object on its right # AND if the distance is ok, return the next child if self._rightchild and distance + max_dist >= self._median: yield self._rightchild # If the function arrives here, the generator will be considered empty # there is no more than two values: the left and the right children
Caller:
# Create an empty list and a list with the current object reference result, candidates = list(), [self] # Loop on candidates (they contain only one element at the beginning) while candidates: # Get the last candidate and remove it from the list node = candidates.pop() # Get the distance between obj and the candidate distance = node._get_dist(obj) # If distance is ok, then you can fill the result if distance <= max_dist and distance >= min_dist: result.extend(node._values) # Add the children of the candidate in the candidate's list # so the loop will keep running until it will have looked # at all the children of the children of the children, etc. of the candidate candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) return result
此代码包含几个智能部分:
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
while
extend()
通常我们传递一个列表给它:
>>> a = [1, 2] >>> b = [3, 4] >>> a.extend(b) >>> print(a) [1, 2, 3, 4]
但是在您的代码中,它获得了一个生成器,这很好,因为:
它之所以有效是因为 Python 并不关心方法的参数是否是列表。Python 需要可迭代对象,因此它可以处理字符串、列表、元组和生成器!这称为鸭子类型,这也是 Python 如此酷的原因之一。但这是另一个故事,对于另一个问题......
你可以停在这里,或者读一点来看看生成器的高级用法:
>>> class Bank(): # Let's create a bank, building ATMs ... crisis = False ... def create_atm(self): ... while not self.crisis: ... yield "$100" >>> hsbc = Bank() # When everything's ok the ATM gives you as much as you want >>> corner_street_atm = hsbc.create_atm() >>> print(corner_street_atm.next()) $100 >>> print(corner_street_atm.next()) $100 >>> print([corner_street_atm.next() for cash in range(5)]) ['$100', '$100', '$100', '$100', '$100'] >>> hsbc.crisis = True # Crisis is coming, no more money! >>> print(corner_street_atm.next()) <type 'exceptions.StopIteration'> >>> wall_street_atm = hsbc.create_atm() # It's even true for new ATMs >>> print(wall_street_atm.next()) <type 'exceptions.StopIteration'> >>> hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty >>> print(corner_street_atm.next()) <type 'exceptions.StopIteration'> >>> brand_new_atm = hsbc.create_atm() # Build a new one to get back in business >>> for cash in brand_new_atm: ... print cash $100 $100 $100 $100 $100 $100 $100 $100 $100 ...
注意:对于 Python 3,使用print(corner_street_atm.__next__())或print(next(corner_street_atm))
print(corner_street_atm.__next__())
print(next(corner_street_atm))
它可用于控制对资源的访问等各种事情。
itertools 模块包含操作可迭代对象的特殊函数。曾经想复制一个生成器吗?连接两个发电机?使用单行对嵌套列表中的值进行分组?Map / Zip不创建另一个列表?
Map / Zip
那么就import itertools.
import itertools
一个例子?让我们看看四马比赛可能的到达顺序:
>>> horses = [1, 2, 3, 4] >>> races = itertools.permutations(horses) >>> print(races) <itertools.permutations object at 0xb754f1dc> >>> print(list(itertools.permutations(horses))) [(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]
迭代是一个包含可迭代对象(实现__iter__()方法)和迭代器(实现__next__()方法)的过程。可迭代对象是您可以从中获取迭代器的任何对象。迭代器是让你迭代可迭代对象的对象。
__iter__()
__next__()
这篇文章中有更多关于循环如何for工作的内容。