在 Python 中检查列表是否包含连续数字

pythonserver side programmingprogramming更新于 2025/12/26 0:44:17

根据数据分析的需要,我们可能需要检查 Python 数据容器中是否存在连续数字。在下面的程序中,我们将找出 Alist 的元素中是否有连续的数字。

使用范围和排序

sorted 函数将按排序顺序重新排列列表中的元素。然后,我们应用范围函数,使用 min 和 max 函数从列表中获取最低和最高数字。我们将上述操作的结果存储在两个列表中,并比较它们是否相等。

示例

listA = [23,20,22,21,24]
sorted_list = sorted(listA)
#sorted(l) ==
range_list=list(range(min(listA), max(listA)+1))
if sorted_list == range_list:
   print("listA has consecutive numbers")
else:
   print("listA has no consecutive numbers")

# 再次检查
listB = [23,20,13,21,24]
sorted_list = sorted(listB)
#sorted(l) ==
range_list=list(range(min(listB), max(listB)+1))
if sorted_list == range_list:
   print("ListB has consecutive numbers")
else:
   print("ListB has no consecutive numbers")

输出

运行上述代码得到以下结果 −

listA has consecutive numbers
ListB has no consecutive numbers

使用 numpy diff 和 sorted

numpy 中的 diff 函数可以找出排序后每个数字之间的差异。我们对这些差异求和。如果所有数字都是连续的,这将匹配列表的长度。

示例

import numpy as np
listA = [23,20,22,21,24]

sorted_list_diffs = sum(np.diff(sorted(listA)))
if sorted_list_diffs == (len(listA) - 1):
   print("listA has consecutive numbers")
else:
   print("listA has no consecutive numbers")

# 再次检查
listB = [23,20,13,21,24]
sorted_list_diffs = sum(np.diff(sorted(listB)))
if sorted_list_diffs == (len(listB) - 1):
   print("ListB has consecutive numbers")
else:
   print("ListB has no consecutive numbers")

输出

运行上述代码得到以下结果 −

listA has consecutive numbers
ListB has no consecutive numbers

相关文章


有用资源