Python 中檢查列表是否包含連續數字


根據我們資料分析的需求,我們可能需要檢查 Python 資料容器中是否存在連續數字。在下面的程式中,我們找出 Alist 的元素中是否存在任何連續數字。

使用 range 和 sorted

sorted 函式將以排序順序重新排列列表的元素。然後,我們應用 range 函式,使用 min 和 max 函式從列表中獲取最低和最高的數字。我們將上述操作的結果儲存在兩個列表中,並比較它們是否相等。

示例

 現場演示

listA = [23,20,22,21,24]
sorted_list = sorted(listA)
#sorted(l) ==
range_list=list(range(min(listA), max(listA)+1))
if sorted_list == range_list:
   print("listA has consecutive numbers")
else:
   print("listA has no consecutive numbers")

# Checking again
listB = [23,20,13,21,24]
sorted_list = sorted(listB)
#sorted(l) ==
range_list=list(range(min(listB), max(listB)+1))
if sorted_list == range_list:
   print("ListB has consecutive numbers")
else:
   print("ListB has no consecutive numbers")

輸出

執行以上程式碼,得到以下結果:

listA has consecutive numbers
ListB has no consecutive numbers

使用 numpy diff 和 sorted

numpy 中的 diff 函式可以在排序後找到每個數字之間的差值。我們取這些差值的總和。如果所有數字都是連續的,則該值將與列表的長度匹配。

示例

 現場演示

import numpy as np
listA = [23,20,22,21,24]

sorted_list_diffs = sum(np.diff(sorted(listA)))
if sorted_list_diffs == (len(listA) - 1):
   print("listA has consecutive numbers")
else:
   print("listA has no consecutive numbers")

# Checking again
listB = [23,20,13,21,24]
sorted_list_diffs = sum(np.diff(sorted(listB)))
if sorted_list_diffs == (len(listB) - 1):
   print("ListB has consecutive numbers")
else:
   print("ListB has no consecutive numbers")

輸出

執行以上程式碼,得到以下結果:

listA has consecutive numbers
ListB has no consecutive numbers

更新於: 2020年5月13日

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.