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

Python 3.x中如何实现指定范围的i与j按序配对遍历输出?

按序配对遍历i和j的解决方案

Got it, I totally get what you're aiming for here—instead of the nested loop's Cartesian product output, you want to pair each i with the corresponding j in order, like 0→10, 1→11, etc. Here's how to do it cleanly in Python 3.x:

核心方法:用zip()函数配对可迭代对象

The zip() built-in function is perfect for this scenario—it takes multiple iterables and returns an iterator that aggregates elements from each one in order. Exactly what you need for side-by-side pairing.

完整代码示例

# 定义范围:i取0-4,j取10-14
for i, j in zip(range(5), range(10, 15)):
    print(i, j)

输出结果

这段代码会精准输出你想要的有序配对:

0 10
1 11
2 12
3 13
4 14

为什么这能行?

  • range(5) 生成序列 0, 1, 2, 3, 4(左闭右开区间)
  • range(10, 15) 生成序列 10, 11, 12, 13, 14
  • zip() 会把两个序列的第1个元素配对,接着第2个,以此类推——当其中一个序列耗尽时停止(这里两个序列长度都是5,刚好完全配对)

额外补充:处理长度不等的情况(可选)

如果你的i和j范围长度不同,且想保留所有元素(哪怕其中一个序列先耗尽),可以用itertools.zip_longest来实现:

from itertools import zip_longest

# 当其中一个序列耗尽时,用None填充空缺
for i, j in zip_longest(range(6), range(10, 15), fillvalue=None):
    print(i, j)

这段代码会先正常配对前5组,最后输出5 None作为补充配对。

内容的提问来源于stack exchange,提问作者Hello.World

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:51:07