如何在python中查找列表中特定范围内的连续项

时间:2016-09-05 10:58:24

标签: python python-3.x

拥有以下python列表[0.0,5.0,2.0,0.0,0.30000000000000004]我想要返回最小连续项目的计数小于0.5

预期结果: [0.0,5.0,2.0,0.0,0.30000000000000004]应该输出2

2 个答案:

答案 0 :(得分:0)

您可以在此处找到工作样本:

list = [0.0, 5.0, 2.0, 0.0, 0.30000000000000004]
listDict = {}

for idx, val in enumerate(list):
    for idx2, val2 in enumerate(list):
        if idx != idx2 and list[idx] != list[idx2] and abs(list[idx] - list[idx2]) < 0.5:
            listDict[str(list[idx])] = True
            listDict[str(list[idx2])] = True

print (len(listDict))

对于实时样本,这是the link

答案 1 :(得分:0)

可能但不稳定的方法:

def number_of_consecutive(data, min_threshold, max_threshold):

    sum_consec, max_value = 0,0

    for element in data:
        if element <= max_threshold and element >= min_threshold:
            sum_consec += 1
            if sum_consec > max_value:
                max_value = sum_consec
        else:
            sum_consec = 0
    return max_value

为给定列表查找范围0到0.5的元素:

print number_of_consecutive([0.0, 5.0, 2.0, 0.0, 0.30000000000000004], 0.0, 0.5)
"2"