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

如何用Python生成0到指定数字的所有两两组合元组?

在Python中生成指定数对的实现方法

方法1:使用标准库itertools.combinations(推荐)

Python的itertools库自带组合生成函数,刚好满足你需要的“两两不同且前数小于后数”的数对需求:

import itertools

num = 4
# 生成0到num的整数序列,取2个元素的所有组合,最后转为元组
result = tuple(itertools.combinations(range(num + 1), 2))
print(result)

运行输出:
((0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))

方法2:手动嵌套循环实现

如果不想依赖标准库,可以用两层循环手动生成符合要求的数对:

num = 4
result_list = []
# 外层循环遍历每个起始数i
for i in range(num + 1):
    # 内层循环从i+1开始,确保j > i
    for j in range(i + 1, num + 1):
        result_list.append((i, j))
# 将列表转为元组
result = tuple(result_list)
print(result)

这段代码的输出和方法1完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 06:38:14