You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python交替遍历生成器列表时如何跳过已耗尽的生成器继续执行

实现思路

  • 将原外层全局异常捕获下移到next()调用处,单独捕获每个迭代器耗尽的StopIteration异常
  • 捕获到异常时直接丢弃已耗尽的迭代器,不重新加入队列
  • 外层循环终止条件改为迭代器列表为空,保证所有迭代器都耗尽才停止遍历
  • 移除原代码中冗余的for iterable in iter_list循环(原有循环未使用迭代变量,属于无效逻辑)

修改后代码

def alternate_all(*args):
    iter_list = []
    for iterable in args:
        iter_list.append(iter(iterable))
    # 只要还有未耗尽的迭代器就继续循环
    while iter_list:
        current_iter = iter_list.pop(0)
        try:
            val = next(current_iter)
            yield val
            # 迭代器未耗尽,重新加回队列尾部等待下一轮取值
            iter_list.append(current_iter)
        except StopIteration:
            # 迭代器已耗尽,直接丢弃不回列
            pass


if __name__ == '__main__':
    for i in alternate_all('abcde','fg','hijk'):
        print(i,end='')

运行验证

执行代码后输出为afhbgicjdke,与预期结果完全一致。

内容的提问来源于stack exchange,提问作者newbiecoder11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 00:39:02