在 Python 中找到一个按顺序排列的数字列表中的缺失数字
给定一个带有排序数字的列表,我们想要找出给定数字范围中缺失的数字。
使用范围
我们可以设计一个 for 循环来检查数字范围,并使用一个带有 not in 运算符的 if 条件来检查缺失元素。
示例
listA = [1,5,6, 7,11,14]
# Original list
print("Given list : ",listA)
# using range
res = [x for x in range(listA[0], listA[-1]+1)
if x not in listA]
# Result
print("Missing elements from the list : \n" ,res)输出
运行以上代码会得到以下结果 −
Given list : [1, 5, 6, 7, 11, 14] Missing elements from the list : [2, 3, 4, 8, 9, 10, 12, 13]
使用 ZIP
ZIP 函数
示例
listA = [1,5,6, 7,11,14]
# printing original list
print("Given list : ",listA)
# using zip
res = []
for m,n in zip(listA,listA[1:]):
if n - m > 1:
for i in range(m+1,n):
res.append(i)
# Result
print("Missing elements from the list : \n" ,res)输出
运行以上代码会得到以下结果 −
Given list : [1, 5, 6, 7, 11, 14] Missing elements from the list : [2, 3, 4, 8, 9, 10, 12, 13]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP