在 Python 中找出列表中缺失的元素


如果我們有一個包含數字的列表,我們可以檢查這些數字是否連續,還可以找出哪些數字在某範圍內缺失,而最高數是最終值。

使用 range 和 max

我們可以設計一個 for 迴圈來使用 not in 運算子檢查某個範圍內缺失的值。然後透過將這些值新增到新列表中,記錄所有這些值,該新列表成為結果集。

示例

 即時演示

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

# Original list
print("Given list : ",listA)

# using range and max
res = [ele for ele in range(max(listA) + 1) if ele 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 :
[0, 2, 3, 4, 8, 9, 10, 12, 13]

使用 set

我們使用 set 函式來儲存給定範圍內的所有唯一值,然後減去給定列表。因此,這會產生包含連續數字中缺失值的結果集。

示例

 即時演示

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

# printing original list
print("Given list : ",listA)

# using set
res = list(set(range(max(listA) + 1)) - set(listA))

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

輸出

執行以上程式碼會產生以下結果 −

Given list : [1, 5, 6, 7, 11, 14]
Missing elements from the list :
[0, 2, 3, 4, 8, 9, 10, 12, 13]

更新於: 26-8-2020

1K+ 瀏覽量

職業生涯精彩啟航

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.