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链接。
又一个TRL;DR
列表中的迭代器 : 下一个 () 返回列表的下一个元素 。
迭代生成器: 下一个 () 将计算苍蝇上的下一个元素( 执行代码)
您可以通过下拨“无论流量如何复杂”,将产出/生成器视为手动运行外部控制流的一种方式(如继续循环一步),然后调用该输出/生成器作为手动运行外部控制流的一种方式。
注意 : 生成器不是一个正常的函数。 它会像本地变量( stack) 一样记住先前的状态 。 请参看其他答案或文章以详细解释 。 生成器只能重复一次 。 您可以不生产, 但不会是那么好, 所以它可以被视为“ 非常好” 的语言糖 。
许多人使用回报而不是生产,但在某些情况下,收益可以更有效和更便于工作。
这里的例子绝对是收成最佳的:
返回( 在函数)
import random
def return_dates():
dates = [] # With 'return' you need to create a list then return it
for i in range(5):
date = random.choice(["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th"])
dates.append(date)
return dates
产出(在函数)
def yield_dates():
for i in range(5):
date = random.choice(["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th"])
yield date # 'yield' makes a generator automatically which works
# in a similar way. This is much more efficient.
呼叫功能
dates_list = return_dates()
print(dates_list)
for i in dates_list:
print(i)
dates_generator = yield_dates()
print(dates_generator)
for i in dates_generator:
print(i)
两种函数都做同样的事情, 但产量使用三行而不是五行, 并且有一个更少的变量要担心。
这是代码的结果:
调
您可以看到两个函数都做相同的事情。 唯一的区别是 返回_ dates () 给出了列表, 而 收益_ dates () 给出了生成器 。
真实生活中的范例就是 逐行读取文件行 或者你只是想制造一个发电机
TL; DR TR; TL; TDR
代替此:
def square_list(n):
the_list = [] # Replace
for x in range(n):
y = x * x
the_list.append(y) # these
return the_list # lines
这样做:
def square_yield(n):
for x in range(n):
y = x * x
yield y # with this one.
每当你发现自己从头开始编出一个清单时, 每一块都取而代之。
这是我第一次"啊哈"节奏节奏
收成是一种含糖的方式 说
构建一系列材料
相同行为 :
>>> for square in square_list(4):
... print(square)
...
0
1
4
9
>>> for square in square_yield(4):
... print(square)
...
0
1
4
9
不同的行为 :
产量是单行道,只能绕过一次。当一个函数有收益时,我们称它为发电机功能。循环者就是它的回报。这些术语是明亮的。我们失去了一个容器的方便,但获得一系列按需要计算并任意延长的能量。
是懒惰的, 它会推卸计算。 函数中含有收益的函数在调用时不会实际执行。 它返回一个循环器对象, 记得它留下的位置。 每次您在调用循环器时( 这发生在换环) 执行步数向下一个产数前进。 返回会提高停止输出并结束序列( 这是换圈的自然结束 ) 。
产量是多功能的。数据不必全部储存在一起, 它可以一次提供一次。 它可以是无限的 。
>>> def squares_all_of_them():
... x = 0
... while True:
... yield x * x
... x += 1
...
>>> squares = squares_all_of_them()
>>> for _ in range(4):
... print(next(squares))
...
0
1
4
9
如果您需要多个通行证,且系列不会太长,请在电话列表上填写:
>>> list(square_yield(4))
[0, 1, 4, 9]
英明地选择“产生”一词,因为这两个含义都适用:
产量——生产或供应(如农业)
...在系列中提供下一个数据
放弃或放弃(与政治权力一样)
...在传动器推进之前,将CPU执行。
就像有人要你做5个纸杯蛋糕一样。如果你做了至少一个纸杯蛋糕,你可以在做其他蛋糕时给他们吃。
In [4]: def make_cake(numbers):
...: for i in range(numbers):
...: yield 'Cake {}'.format(i)
...:
In [5]: factory = make_cake(5)
这里称为发电机, 它会做蛋糕。 如果您叫作 Make_ 函数, 您可以得到一个发电机, 而不是运行此函数。 这是因为当输出关键字出现在一个函数中时, 它会变成一个生成器 。
In [7]: next(factory)
Out[7]: 'Cake 0'
In [8]: next(factory)
Out[8]: 'Cake 1'
In [9]: next(factory)
Out[9]: 'Cake 2'
In [10]: next(factory)
Out[10]: 'Cake 3'
In [11]: next(factory)
Out[11]: 'Cake 4'
他们消耗了所有的蛋糕, 但他们又要求一个。
In [12]: next(factory)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-12-0f5c45da9774> in <module>
----> 1 next(factory)
StopIteration:
并且他们被告知不要问更多的问题。 所以一旦你消耗了发电机, 你就会用它做。 如果你想要更多的蛋糕,你需要再打电话做蛋糕。 这就像再订一份蛋糕。
In [13]: factory = make_cake(3)
In [14]: for cake in factory:
...: print(cake)
...:
Cake 0
Cake 1
Cake 2
您也可以使用上面的生成器来循环。
举个例子:假设你每次问密码时都想要随机密码。
In [22]: import random
In [23]: import string
In [24]: def random_password_generator():
...: while True:
...: yield ''.join([random.choice(string.ascii_letters) for _ in range(8)])
...:
In [25]: rpg = random_password_generator()
In [26]: for i in range(3):
...: print(next(rpg))
...:
FXpUBhhH
DdUDHoHn
dvtebEqG
In [27]: next(rpg)
Out[27]: 'mJbYRMNo'
这里的 rpg 是一个生成器, 它可以生成无限数量的随机密码。 所以我们也可以说, 当我们不知道序列的长度时, 生成器是有用的, 不同于列表, 列表中有一定数量的元素 。