[英]Why doesn't my generator function produce correct values?
我為我的編程 class 編寫了一個生成器 function 的任務,該生成器將一個 int ( n
) 和一個生成器 ( gen
) 作為 arguments 並生成給定生成器的前n
元素。 我寫:
from typing import Iterator, Any
def basic_generator(n): # Just a generator function to be able to test it out
while True:
yield n
n += 1
def tryout(n: int, gen: Iterator[Any]) -> Iterator[Any]:
i = 0
while i < n:
next(gen)
yield i
i = i + 1
在我收到的反饋中,它告訴我這是錯誤的,但沒有說明原因。 我知道它不起作用,但我不明白為什么。 有人可以向我解釋一下嗎?
您正在yield
計數器而不是value ...更改為yield next(gen)
。
使用for
循環而不是while
也會更干凈:
def tryout(n: int, gen: Iterator[Any]) -> Iterator[Any]:
for _ in range(n):
yield next(gen)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.