Fly*_*ble 9 python iterable generator
我不能使用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并继续完成.
Pad*_*ham 19
使用默认值1for next,以便至少打印一次字母:
def iteration(letters, numbers):
# create iterator from numbers
it = iter(numbers)
# get every letter
for x in letters:
# either print in range passed or default range of 1
for z in range(next(it, 1)):
yield x
Run Code Online (Sandbox Code Playgroud)
输出:
In [60]: for s in iteration(['a', 'b', 'c', 'd', 'e'], [1,2,5]):
....: print(s)
....:
a
b
b
c
c
c
c
c
d
e
Run Code Online (Sandbox Code Playgroud)