检查列表是否在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
用numpydiff和排序
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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿