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链接。
也可以将数据发送回生成器!
事实上,正如这里许多答案所解释的那样,利用产量产生一个发电机。
您可以使用产出关键字将数据发送回“实时”生成器。
示例:
假设我们有一种方法可以从英语翻译成其他语言。 在开始的时候, 它会做一些很重的事情, 应该做一次。 我们希望这个方法可以永远运行( 不知道为什么..... . :) , 并且收到要翻译的单词 。
def translator():
# load all the words in English language and the translation to 'other lang'
my_words_dict = {'hello': 'hello in other language', 'dog': 'dog in other language'}
while True:
word = (yield)
yield my_words_dict.get(word, 'Unknown word...')
运行中 :
my_words_translator = translator()
next(my_words_translator)
print(my_words_translator.send('dog'))
next(my_words_translator)
print(my_words_translator.send('cat'))
将打印 :
dog in other language
Unknown word...
概括如下:
使用发件人内部发送方法将数据发送回发件人。要允许,使用 a (ield) 。
- 功能 - 返回。
发电机 -- -- 产量(含有一个或多个产量和零或更多回报率)。
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
注:放弃不应在尝试中.最终建造。
生成关键字用于查点/字符,其中函数预期将返回一个输出。我想引用这个非常简单的例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
发电机可以使个别经过处理的物品立即得到处理(不必等待整个收集过程的处理),下面的例子说明了这一点。
import time
def get_gen():
for i in range(10):
yield i
time.sleep(1)
def get_list():
ret = []
for i in range(10):
ret.append(i)
time.sleep(1)
return ret
start_time = time.time()
print('get_gen iteration (individual results come immediately)')
for i in get_gen():
print(f'result arrived after: {time.time() - start_time:.0f} seconds')
print()
start_time = time.time()
print('get_list iteration (results come all at once)')
for i in get_list():
print(f'result arrived after: {time.time() - start_time:.0f} seconds')
get_gen iteration (individual results come immediately)
result arrived after: 0 seconds
result arrived after: 1 seconds
result arrived after: 2 seconds
result arrived after: 3 seconds
result arrived after: 4 seconds
result arrived after: 5 seconds
result arrived after: 6 seconds
result arrived after: 7 seconds
result arrived after: 8 seconds
result arrived after: 9 seconds
get_list iteration (results come all at once)
result arrived after: 10 seconds
result arrived after: 10 seconds
result arrived after: 10 seconds
result arrived after: 10 seconds
result arrived after: 10 seconds
result arrived after: 10 seconds
result arrived after: 10 seconds
result arrived after: 10 seconds
result arrived after: 10 seconds
result arrived after: 10 seconds