在列表中查找条件转折点的索引

2024-05-15 14:37:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,我想确定转折点的索引

仅当前5个数据点或以上显示下降时,才视为转折点

da_list = [100,99,98,105,94,78,52,51,49,48,47,50,40,41,39,33,36,22] 
                      ^                    ^        ^
                      not                  is      not

用一种笨拙的方式,它告诉我们索引是10:

for idx, each in enumerate(da_list):
    if da_list[idx - 5] > da_list[idx - 4] and \
    da_list[idx - 4] > da_list[idx - 3] and \
    da_list[idx - 3] > da_list[idx - 2] and \
    da_list[idx - 2] > da_list[idx - 1] and \
    da_list[idx - 1] > da_list[idx] and \
    da_list[idx] <= da_list[idx + 1]:
        print (idx, each)

有什么更聪明的方法可以做到这一点,特别是如果列表变得更长,需要减少100个数据点


Tags: and数据in列表foris方式not
2条回答

您可以从itertools中尝试groupby

from itertools import groupby

da_list = [22,36,33,39,41,40,50,47,48,49,51,52,78,94,105,98,99,100]
diff = list(map(lambda x: 1 if x>=0 else -1 , da_list[0:1] + [e-da_list[i-1] for i,e in enumerate(da_list[1:], 1)]))

carrying_index = -1
for gp_name, grp in groupby(diff):
    length = len(list(grp))
    carrying_index += length
    if(gp_name == -1 and length >= 5):
        print(da_list[carrying_index])

另一个更简单的方法

from itertools import groupby

da_list = [100,99,98,105,94,78,52,51,49,48,47,50,40,41,39,33,36,22,21,20]
diff = da_list[0:1] + [e-da_list[i-1] for i,e in enumerate(da_list[1:], 1)]


for g_name, grp in groupby(zip(da_list, range(len(da_list)), diff), key=lambda x: x[-1]>=0):
    if not g_name:
        l_group = list(grp)
        if(len(l_group) >= 5):
            print('index: ', l_group[-1][1])
            print('value: ', l_group[-1][0])
            
            
# index:  10
# value:  47

这是一种简单而有效的方法

data = [100,99,98,105,94,78,52,51,49,48,47,50,40,41,39,33,36,22]

num_decreases = 0
old_val = data[0]
turn_points = list()
REQUIRED_DECREASES = 5
for i, d in enumerate(data[1:]):
    if d - old_val < 0:
        num_decreases += 1
    else:
        if num_decreases >= REQUIRED_DECREASES:
            turn_points.append((i, d))
        num_decreases = 0
    old_val = d

print(turn_points)

相关问题 更多 >