Python 中检查列表是否包含连续数字
根据我们数据分析的需求,我们可能需要检查 Python 数据容器中是否存在连续数字。在下面的程序中,我们找出 Alist 的元素中是否存在任何连续数字。
使用 range 和 sorted
sorted 函数将以排序顺序重新排列列表的元素。然后,我们应用 range 函数,使用 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")
# 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 和 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")
# 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP