【问题标题】:How to count pair of peaks indexes including last entry?如何计算包括最后一个条目的峰值索引对?
【发布时间】:2019-08-26 13:59:34
【问题描述】:

我在尝试将索引的最后一个条目包含到输出时遇到了障碍。 一对峰值由列表中大于 3 的一组相邻值定义。 如何将最后一个条目的索引包含在输出中?

data_series_1 = [6,4,5,2,2,0,5,4,4,2,0,2,2,1,4,2,2,5,4,6]
def paired_peaks(data_series,threshold):
    peaks =[]
    for k in range(0,len(data_series)-1):
        y_b = data_series[k-1]
        y= data_series[k]
        y_a = data_series[k+1]

        if y>threshold:
            if y_b>threshold or y_a>threshold:
                peaks.append(k)

    return peaks

print(paired_peaks(data_series_1,3))

我希望它是[0, 1, 2, 6, 7, 8, 17, 18, 19],但实际输出是[0, 1, 2, 6, 7, 8, 17, 18]

【问题讨论】:

  • 您的循环在检查最后一个索引之前退出...

标签: python python-3.x list for-loop indexing


【解决方案1】:

for 循环结束时,您的问题就会发生。当您到达最后一个元素时,您正在尝试读取它之后的元素,并且该元素不存在。

可能会欺骗你的是因为data_series[-1] 实际上读取了最后一个元素而不是上升错误。

现在,我不知道你的程序的意图是什么,你想读取第一个元素而不是不存在的元素吗?我假设你这样做是因为第一个元素与最后一个元素和第二个元素进行了比较。

为了解决你的问题,我做了:

data_series_1 = [6,4,5,2,2,0,5,4,4,2,0,2,2,1,4,2,2,5,4,6]
def paired_peaks(data_series,threshold):
    peaks =[]
    l = len(data_series)
    for k in range(l):
        y_b = data_series[k-1]
        y= data_series[k]
        y_a = data_series[(k+1)%l]
    if y > threshold:
        if y_b > threshold or y_a > threshold:
            peaks.append(k)
    return peaks
print(paired_peaks(data_series_1,3))

我添加了将data_series 的长度写入变量l,然后改为使用data_series[(k+1)%l] 检查模块值,以确保读取您的第一个元素而不是不存在的元素。

这按预期工作,但是我建议您检查是否要将第一个元素与最后一个元素进行比较,以及是否希望将最后一个元素与第一个元素进行比较。

【讨论】:

    【解决方案2】:

    这将解决您的问题:

    data_series_1 = [6,4,5,2,2,0,5,4,4,2,0,2,2,1,4,2,2,5,4,6]
    def paired_peaks(data_series,threshold):
        peaks =[]
        for k in range(len(data_series)):
            y_b = data_series[k-1] if k - 1 in range(len(data_series)) else 0
            y= data_series[k]
            y_a = data_series[k+1] if k + 1 in range(len(data_series)) else 0
    
            if y>threshold:
                if y_b>threshold or y_a>threshold:
                    peaks.append(k)
    
        return peaks
    
    print(paired_peaks(data_series_1,3))
    
    # returns: [0, 1, 2, 6, 7, 8, 17, 18, 19]
    

    您的计算过早停止的原因是:range(0,len(data_series)-1)。您提前退出了循环。我还在您的代码中添加了if k +/- 1 in range(len(data_series)) else 0,因为列表的第一项和最后一项没有邻居,所以我假设它应该为零。对于最后一项,否则会引发错误,因为它超出了范围。对于第一项,这并没有引发错误,因为 data_series_1[-1] 返回列表中的 last 项,但我认为这不是您的代码的意图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 2012-10-14
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 2019-10-28
      • 2023-02-23
      相关资源
      最近更新 更多