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

Python中获取含增减区间的整数序列(含起止点)的最优方法

获取两个数字间所有整数(含起止点并保持顺序)的实现方案

需求:获取两个数字之间的所有整数(包含起止点),第一个数字可能小于、大于或等于第二个数字,同时要保持序列的顺序。

现有实现方案

numpy.linspace方案

利用numpy的linspace函数,通过指定生成的元素数量覆盖所有整数:

import numpy as np

tps = ((7, 2), (0, 3), (9, -2), (-3, 4), (5, 5))

for tp in tps:
    print(np.linspace(tp[0], tp[1], num=abs(tp[0] - tp[1]) + 1, dtype=int))

range变通方案

通过判断两个数的大小,决定生成正序序列还是反转序列:

tps = ((7, 2), (0, 3), (9, -2), (-3, 4), (5, 5))

for tp in tps:
    if tp[0] < tp[1]:
        print([num for num in range(min(tp), max(tp) + 1)])
    else:
        print([num for num in range(min(tp), max(tp) + 1)][::-1])

更简便的原生Python实现

直接利用range的步长参数,无需额外反转操作,逻辑更简洁:

tps = ((7, 2), (0, 3), (9, -2), (-3, 4), (5, 5))

for tp in tps:
    a, b = tp
    step = 1 if a <= b else -1
    # 结束值加step确保包含b
    print(list(range(a, b + step, step)))

该方案无需引入numpy依赖,仅用原生Python即可完成,完美适配所有场景:

  • 当a < b时,步长为1,生成正序序列
  • 当a > b时,步长为-1,生成逆序序列
  • 当a == b时,生成仅包含该数字的单元素列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:45:38