我有值列表,我正在寻找方法来跟踪这些值是否低于某个值,然后它们是否回到某个值以上(可能是次数(
所以假设我的 lisy 看起来像:
list1 = [20, 18, 16, 15, 13, 12, 16, 17, 14, 11, 16]
我需要一些东西来告诉我,值在最初低于 15 后回升到 15 以上两次或 x 次。有人知道如何解决这个问题吗?
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)
您可以简单地检查 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