【问题标题】:Return array indices from function从函数返回数组索引
【发布时间】:2018-11-14 10:50:13
【问题描述】:

我有一个数组和函数,我希望该函数返回一个索引列表,其中两个连续元素的差值超过一个阈值。

我有:

def func (y, t=100):
    for i in range(1, len(y)): #Range skips 1st element
        if abs(y[i] - y[i-1]) > t:
            return(i)

我面临的问题是这个函数只返回我的 if 语句为真的第一个索引。我如何获得其余的?

【问题讨论】:

  • yield i 并在list 中收集项目(换句话说,将您的函数转换为生成器函数)
  • 请勿退货。抓住它。

标签: python python-3.x function indexing


【解决方案1】:

使用list comprehension,您可以这样做:

代码:

def peak_detect(in_data, threshold=100):
    return [i for i, (x, y) in enumerate(zip(in_data, in_data[1:]))
            if abs(y - x) >= threshold]

测试代码:

data = [1, 2000, 2001, 4000]

print(peak_detect(data))

结果:

[0, 2]

【讨论】:

    【解决方案2】:

    有两种方法。首先,yield 而不是 return 会给你一个生成器:

    def func (y, t=100):
        for i in range(1, len(y)): #Range skips 1st element
            if abs(y[i] - y[i-1]) > t:
                yield(i)
    

    或者在你的函数中添加一个列表:

    def func (y, t=100):
        output = []
        for i in range(1, len(y)): #Range skips 1st element
            if abs(y[i] - y[i-1]) > t:
                output.append(i)
        return output
    

    【讨论】:

      【解决方案3】:
      def peak_detect (y_, threshold=100):
          indicesList = []
          for i in range(1, len(y_)): #Range skips 1st element
              if abs(y[i] - y[i-1]) > threshold:
                  indicesList.append(i)
          return(indicesList)
      

      【讨论】:

        猜你喜欢
        • 2021-05-01
        • 2019-08-15
        • 2011-10-06
        • 2014-09-16
        • 2020-06-22
        • 1970-01-01
        • 2016-03-24
        • 1970-01-01
        • 2016-11-08
        相关资源
        最近更新 更多