python處理孤立的異常點

假設有一個列表,a = [61, 40, 70, 80, 86, 50, 88, 33, 76, 64],保存的是設備的狀態值隨時間的變化,超過60即爲異常,可是對於孤立的異常點,咱們須要將其忽略,只有連續的異常點才認爲是真正的異常,須要統計異常的次數(固然也能夠有其餘的操做,刪除孤立的異常點等等)。spa

處理的代碼以下:code

def get_above_threshold_num(device_status, threshold):
    if not isinstance(device_status, list) or not isinstance(threshold, int):
        return
    num = 0
    count = len(device_status)
    for index, value in enumerate(device_status):
        if value >= threshold:
            if (0 <= index - 1 < count and device_status[index - 1] >= threshold) or (0 <= index + 1 < count and device_status[index + 1] >= threshold):
                num += 1
    return num


if __name__ == "__main__":
    a = [61, 40, 70, 80, 86, 50, 88, 33, 76, 64]
    b = get_above_threshold_num(a, 80)
    print(b)

思路即就是遍歷列表中的元素,若是大於等於閾值,則找到它的前一個元素和後一個元素,只要有一個元素是大於等於閾值的,則進行統計。blog

相關文章
相關標籤/搜索