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

标签 python

是否有一种惯用的方法来提前完成迭代器,以便任何进一步的 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/

相关文章:

python - 函数速度提升 : Convert ints to list of 32bit ints

python - 如何找到列表中最长的列表?

python - 在 Python 中下载网页及其所有资源文件

Python 2.7 - statsmodels - 格式化和编写摘要输出

python - SVM 损失函数的梯度

python - 查看 Python 函数的代码

python - 如何在 Python 中并行处理列表?

python - 使用 Spotfire 的日期过滤器和相对日期输入框

python - 在pandas交叉表中,如何计算加权平均值?以及如何添加行和列总计?

python - 我收到以下错误需要超过 1 个值才能解包