How do I detect contiguous sublists with values above a certain threshold?
我有非常基本的编程技能。我的问题是如何检测给定列表的连续子列表,这样子列表的所有成员都高于某个阈值。列表中可能有多个这样的子列表。例如,我们有一个名为list1的列表,如下所示:
1 | list1 = [5, 10, 9, 11, 22, 19, 23, 2, 2, -1, 1, 4, 5, 19, 20, 40, 32, 34, 7, 3, -2, 4, 5 , 7 , 22, 23, 24, 35] |
我希望能够检测到高于18的子列表,并检索返回其索引的子列表中的最低值。在
不过,只要找到与模式不匹配的值,就可以迭代并临时存储值以及与模式匹配的值的索引。然后你需要找到最小的数字并存储它的索引值清除临时模式存储并继续迭代直到到达末尾
快速和肮脏在python中可能看起来像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | def get_min_indx(data): emin = data[0] for e in data: # check values if e[1] < emin[1]: emin = e return emin[0] def find_pattern(data,pattern_threshold): pattern_found = [] indxs = [] for idx,e in enumerate(data): if e > pattern_threshold: # found an element: store it's index and it's value pattern_found.append((idx,e)) elif len(pattern_found) != 0: indxs.append(get_min_indx(pattern_found)) # reset our pattern_storage pattern_found = [] if len(pattern_found) != 0: indxs.append(get_min_indx(pattern_found)) return indxs list1 = [5, 10, 9, 11, 22, 19, 23, 2, 2, -1, 1, 4, 5, 19, 20, 40, 32, 34, 7, 3, -2, 4, 5 , 7 , 22, 23, 24, 35] pattern_threshold = 18 print(find_pattern(list1,pattern_threshold)) |
如果我明白你在找什么,这就可以了。我们的想法是通过我们的列表,把大于18的数字列成较小的列表(
1 2 3 4 5 6 7 8 9 10 11 12 | list1 = [5, 10, 9, 11, 22, 19, 23, 2, 2, -1, 1, 4, 5, 19, 20, 40, 32, 34, 7, 3, -2, 4, 5 , 7 , 22, 23, 24, 35] templist = [] for i,l in enumerate(list1): if(l > 18): templist.append(l) else: if len(templist) > 0: print(i-len(templist)+templist.index(min(templist)),min(templist)) templist = [] if len(templist) > 0: print(i-len(templist)+templist.index(min(templist)),min(templist)) templist = [] |