我不能使用itertools
所以编码看起来很简单,但是我在思考算法时遇到了麻烦,以便在所有迭代都被完全处理之前保持生成器运行.
该函数的想法是将2个迭代作为这样的参数......
(['a', 'b', 'c', 'd', 'e'], [1,2,5])
它的作用是产生这些价值......
a, b, b, c, c, c, c, c
但是,如果第二个迭代首先耗尽元素,则函数只会迭代剩余值一次......
所以剩下的值会像这样迭代:
d, e
def iteration(letters, numbers):
times = 0
for x,y in zip(letters, numbers):
try:
for z in range(y):
yield x
except:
continue
[print(x) for x in iteration(['a', 'b', 'c', 'd'], [1,2,3])]
Run Code Online (Sandbox Code Playgroud)
我无法忽略第一个StopIteration并继续完成.