给定一个带有排序数字的列表,我们想找出给定数字范围中缺少哪些数字。
我们可以设计一个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功能
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]