在 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 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

立即開始
廣告