在 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