根据列表跟踪值低于或高于阈值的次数

时间:2017-11-19 23:32:50

标签: python python-3.6

我有值列表,我正在寻找方法来跟踪这些值是否低于某个值,然后如果它们重新高于它(可能是次数)

所以让我说我的朦胧看起来像:

list1 = [20, 18, 16, 15, 13, 12, 16, 17, 14, 11, 16]

我需要一些能告诉我的东西,在最初低于15之后,价值回升到15以上或x次。 任何人都知道如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

pos_count = 0
neg_count = 0 

for x in range(len(list1)-1):
    if list1[x] <= 15 and list1[x + 1] > 15:
        neg_count += 1
    elif list1[x] >= 15 and list1[x + 1] < 15:
        pos_count += 1

print(pos_count)
print(neg_count)

答案 1 :(得分:0)

你可以简单地检查15的负面/正面差异。 像这样:

l = [20, 18, 16, 15, 13, 12, 16, 17, 14, 11, 16] #Your list

import numpy as np
arr = np.asarray(l) #Convert to numpy-array

#Now apply the function to check the difference from 15
result = np.apply_along_axis(lambda x: x - 15, axis=0, arr=arr)

这会导致: 数组([5,3,1,0,-2,-3,1,2,-1,-4,1])

如果要检查所有正值,可以这样做:

pos = result[result >= 0] #All positive values
neg = result[result <  0] #All negative values

如果您想计算这种情况发生的频率,您可以计算长度:

len(pos) #Number of positives
len(neg) #Number of negatives