gpt4 book ai didi

python - 我可以将迭代器标记为过早完成吗?

转载 作者:太空宇宙 更新时间:2023-11-03 13:42:42 25 4
gpt4 key购买 nike

是否有一种惯用的方法来提前完成迭代器,以便任何进一步的 next() 引发 StopIteration? (我可以想到丑陋的方法,比如滥用 itertools.takewhile 或丢弃值直到用完)。

编辑:

我的算法将 n 个未知可变长度的迭代器作为输入。它使用 izip_longest() 从 n 元组中的每一项中读取一项,直到所有项都用完。有时我发现我想根据某些运行时标准提前停止来自其中一个迭代器的输入,并将其替换为 izip_longest() 提供的默认值流。我能想到的侵入性最小的方法是以某种方式“完成”它。

最佳答案

来自 itertools Recipes :

def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(islice(iterator, n, n), None)

关于python - 我可以将迭代器标记为过早完成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27473417/

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