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

根据我们数据分析的需求,我们可能需要检查python数据容器中是否存在序号。在下面的程序中,我们发现Alist的元素中是否有连续的数字。

带范围和排序

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

示例

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")

# Checking again
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和排序

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")

# Checking again
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