1. 程式人生 > >python找出列表中大於某個閾值的資料段

python找出列表中大於某個閾值的資料段

該演算法實現對列表中大於某個閾值(比如level=5)的連續資料段的提取,具體效果如下:

找出list裡面大於5的連續資料段:

list = [1,2,3,4,2,3,4,5,6,7,4,6,7,8,5,6,7,3,2,4,4,4,5,3,6,7,8,9,8,6,1]

輸出:

[[6, 7], [6, 7, 8], [6, 7], [6, 7, 8, 9, 8, 6]]

演算法實現:

# -*- coding: utf-8 -*-

"""
--------------------------------------------------------
# @Version : python3.6
# @Author  : wtg
# @File    : data_search.py
# @Software: PyCharm
# @Time    : 2018/12/17 14:44
--------------------------------------------------------
# @Description: 
--------------------------------------------------------
"""

def data_search(data, level):
    list = []
    temp = []
    for i in range(len(data)):
        if data[i] > level:
            temp.append(data[i])
        else:
            list.append(temp)
            temp = []
    return [i for i in list if i]

if __name__ == '__main__':
    list = [1,2,3,4,2,3,4,5,6,7,4,6,7,8,5,6,7,3,2,4,4,4,5,3,6,7,8,9,8,6,1]
    ret  = data_search(list, 5)
    print("input: ",list)
    print("output: ",ret)

效果如下: