Python | 检查列表是否包含连续整数
检查列表是否包含连续的整数
给定一个数字列表,编写一个Python程序来检查该列表是否包含连续的整数。
示例
Input : [2, 3, 1, 4, 5] Output : True Input : [1, 2, 3, 5, 6] Output : False 方法1: 使用sorted()
我们可以将排序列表与列表的最小和最大整数范围列表进行比较
# Python3 Program to Create list # with integers within given range def checkConsecutive(l): return sorted(l) == list(range(min(l), max(l)+1)) # Driver Code lst = [2, 3, 1, 4, 5] print(checkConsecutive(lst)) 输出:
True 方法2: 使用numpy
Numpy模块提供了一个函数diff(),用于计算沿着给定轴的第n个离散差值。我们找到排序列表的迭代差,并检查它是否等于1。
# Python3 Program to Create list # with integers within given range import numpy as np def checkConsecutive(l): n = len(l) - 1 return (sum(np.diff(sorted(l)) == 1) >= n) # Driver Code lst = [2, 3, 1, 4, 5] print(checkConsecutive(lst)) 输出:
True 方法3
- 对列表排序。这一步是必要的,因为我们要检查列表中的数字是否是连续的,而不是它们的顺序。
- 使用列表解析来检查排序列表中的所有元素是否都是连续的。如果所有元素都是连续的,那么列表解析将返回一个True值的列表。否则,它将返回一个至少有一个False值的列表。
- 使用all()函数检查列表中的所有元素是否都为True。如果所有元素都为True,则列表包含连续的数字。否则,列表不包含连续的数字。
#given list lst = [2, 3, 1, 4, 5] #sort the list sorted_lst = sorted(lst) #check if all elements are consecutive is_consecutive = all(sorted_lst[i] == sorted_lst[i-1] + 1 for i in range(1, len(sorted_lst))) #print the result print(is_consecutive) # prints True 输出:
True