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

Python双并行循环终止其一后仍继续执行另一循环的实现方法

实现双向并行遍历单边耗尽后仍继续运行的方案

你原本使用的zip()函数会在最短的迭代器耗尽时直接终止遍历,要实现单边耗尽后补None继续运行到最长迭代器结束,可以使用Python标准库itertools提供的zip_longest()方法,它会自动用填充值补全较短的迭代器。

完整实现代码

from itertools import zip_longest

s = '0123456789'
index = 5

# 左侧倒序遍历到开头,右侧正序遍历到末尾
for left_char, right_char in zip_longest(s[index-1::-1], s[index+1:]):
    print(left_char, right_char)

不同入参测试结果

  • index=5时输出:
4 6
3 7
2 8
1 9
0 None
  • index=3时输出:
2 4
1 5
0 6
None 7
None 8
None 9
  • index=7时输出:
6 8
5 9
4 None
3 None
2 None
1 None
0 None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:06:02