[英]Best way of getting both the yield'ed output and return'ed value of a generator in Python
給定一個帶有返回值的簡單生成器:
def my_generator():
yield 1
yield 2
return 3
我正在尋找一個簡單的 function ,它返回生成的列表和返回值。
>>> output_and_return(my_generator())
([1, 2], 3)
似乎沒有任何干凈的方法可以做到這一點。 在另一個生成器中,您可以使用value = yield from my_generator()
,這將為您獲取返回值,但不會直接為您提供 output 列表本身。
我能想到的最接近的方法是將它包裹在一個捕獲返回值的迭代器上:
class Generator:
def __init__(self, gen):
self.gen = gen
def __iter__(self):
self.value = yield from self.gen
def output_and_return(self):
return list(self), self.value
Generator(my_generator()).output_and_return()
哪個有效,但它絕不簡單或干凈。 有誰知道提取值列表以及生成器的返回值而不將其包裝在另一個 class 中的更簡單方法?
我想我們可以像這樣從 StopIteration 異常中提取它:
def output_and_return(iterator):
output = []
try:
while True:
output.append(next(iterator))
except StopIteration as e:
return output, e.value
不是最干凈的代碼,但比 class 替代方案好很多。
沒有將其包裹在另一個 class 中?
也許只用 function 代替?
版本 1:
def output_and_return(it):
def with_result():
yield (yield from it)
*elements, result = with_result()
return elements, result
版本 2:
def output_and_return(it):
result = None
def get_result():
nonlocal result
result = yield from it
return list(get_result()), result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.