在 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]

更新于: 26-8-2020

836 次浏览

开启你的职业生涯

完成课程并获得认证

立即开始
广告
© . All rights reserved.