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

如何判断Python列表中的数字是否连续?

判断列表是否为连续递增数字的Python实现方案

问题分析

你的代码存在两个核心问题:

  1. 未定义变量x,运行时会直接抛出NameError;
  2. 仅尝试检查一对相邻元素,没有遍历列表中所有相邻位置完成完整验证。

方案一:基于循环的遍历验证

这是对你初始思路的直接完善,通过循环遍历列表中从第二个元素开始的所有位置,逐一验证当前元素与前一个元素的差值是否为1:

def is_consecutive(a_list):
    # 处理空列表或单元素列表的边界情况
    if len(a_list) <= 1:
        print("The list is consecutive.")
        return
    
    # 遍历从索引1开始的所有元素
    for x in range(1, len(a_list)):
        # 只要有一对相邻元素差值不为1,直接判定不连续并返回
        if a_list[x] - a_list[x-1] != 1:
            print("The list is not consecutive.")
            return
    
    # 所有相邻元素都满足条件,判定连续
    print("The list is consecutive.")

# 测试示例
is_consecutive([1,2,3,4,5])  # 输出:The list is consecutive.
is_consecutive([1,3,4])      # 输出:The list is not consecutive.

方案二:用all()函数简化实现

利用Python内置的all()函数,可以更简洁地完成所有相邻元素的验证逻辑,代码可读性更高:

def is_consecutive(a_list):
    if len(a_list) <= 1:
        result = True
    else:
        # 生成所有相邻元素差值的验证条件,all()会检查所有条件是否为True
        result = all(a_list[i] - a_list[i-1] == 1 for i in range(1, len(a_list)))
    
    print("The list is consecutive." if result else "The list is not consecutive.")
    return result

# 测试示例
is_consecutive([2,3,4])      # 输出:The list is consecutive.
is_consecutive([5,6,8])      # 输出:The list is not consecutive.

补充说明

  • 边界情况处理:空列表或仅含单个元素的列表,通常默认视为连续(若你的业务逻辑有特殊要求,可自行调整这部分判断);
  • 提前终止:方案一中的循环会在发现不满足条件的元素时立刻返回,避免不必要的遍历,性能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 12:18:17