该函数为此对象创建一个生成器。流生成器必须等于原始流。
gen = gen_stream (9, [(4,111), (7,12)])
list (gen) [0, 0, 0, 0, 111, 0, 0, 12, 0]
代码:
from itertools import count
def gen_stream(total, sorted_iterable, extractor=lambda x: x):
sorted_iterable = dict(map(extractor, sorted_iterable))
iterable = count() if total is None else range(total)
for i in iterable:
yield sorted_iterable.get(i, 0)
#gen = gen_stream(9,[(4,111),(7,12)])
#list(gen)
输出:
[0, 0, 0, 0, 111, 0, 0, 12, 0]
现在的问题是:如何在不将可迭代转换为字典的情况下完成任务?据我了解:
sorted_iterable = dict(map(extractor, sorted_iterable))