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

pythonserver side programmingprogramming更新于 2025/10/12 13:32:17

如果我们有一个包含数字的列表,我们可以检查这些数字是否连续,还可以找出数字范围内缺失的数字,将最高数字作为最终值。

使用范围和最大值

我们可以设计一个 for 循环,使用 not in 运算符检查范围内的值是否缺失。然后通过将所有这些值添加到新列表中来捕获它们,该列表将成为结果集。

示例

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

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

# 使用范围和最大值
res = [ele for ele in range(max(listA) + 1) if ele not in listA]

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

输出

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

给定列表: [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]

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

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

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

输出

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

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

相关文章


有用资源