gpt4 book ai didi

python - 继续直到所有迭代器完成 Python

转载 作者:太空狗 更新时间:2023-10-29 20:37:55 25 4
gpt4 key购买 nike

我不能使用 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])]

我很难忽略第一个 StopIteration 并继续完成。

最佳答案

为下一个使用默认值 1 以便至少打印一次字母:

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

输出:

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

关于python - 继续直到所有迭代器完成 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30113214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com