在 Python 中查找排序列表范围内的缺失数字

pythonserver side programmingprogramming更新于 2025/10/12 14:04:17

给定一个包含排序数字的列表,我们想要找出给定数字范围内缺失的数字。

使用范围

我们可以设计一个 for 循环来检查数字范围,并使用 if 条件和 not in 运算符来检查缺失的元素。

示例

listA = [1,5,6, 7,11,14]

# 原始列表
print(" 给定列表: ",listA)

# 使用 range(范围)
res = [x for x in range(listA[0], listA[-1]+1)
                              if x not in listA]
# 结果
print("Missing elements from the list : \n" ,res)

输出

运行上述代码得到以下结果 −

给定列表: [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("给定列表: ",listA)

# 使用 zip
res = []
for m,n in zip(listA,listA[1:]):
   if n - m > 1:
      for i in range(m+1,n):
         res.append(i)

# 结果
print("Missing elements from the list : \n" ,res)

输出

运行上述代码得到以下结果 −

给定列表: [1, 5, 6, 7, 11, 14]
Missing elements from the list :
[2, 3, 4, 8, 9, 10, 12, 13]

相关文章


有用资源