Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取numpy数组中具有最小长度的相同项序列的范围_Python_Arrays_Numpy - Fatal编程技术网

Python 获取numpy数组中具有最小长度的相同项序列的范围

Python 获取numpy数组中具有最小长度的相同项序列的范围,python,arrays,numpy,Python,Arrays,Numpy,考虑一个数组,其中的条目完全由-1或1组成。如何获取包含1且最小长度为t(例如t=3)的所有片的范围 例如: >>>a=np.array([-1,-1,1,1,1,1,1,-1,1,-1,-1,1,1,1,1], dtype=int) >>> a array([-1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, 1]) 然后,t=3的期望输出将是[(2,7)、(11,15)]一种使用和的方法- 我

考虑一个数组,其中的条目完全由-1或1组成。如何获取包含1且最小长度为
t
(例如
t=3
)的所有片的范围

例如:

>>>a=np.array([-1,-1,1,1,1,1,1,-1,1,-1,-1,1,1,1,1], dtype=int)
>>> a
array([-1, -1,  1,  1,  1,  1,  1, -1,  1, -1, -1,  1,  1,  1,  1])
然后,
t=3
的期望输出将是
[(2,7)、(11,15)]

一种使用和的方法-


我不太了解numpy,但使用简单的函数不是更好吗

def slices(a, t):
    start = None
    i = 0 # index into array
    slices = [] 
    for val in a:
        if a[i] == 1: # start of sequence
            if start is None:
                start = i
        else: # -1 end of sequence
            if start is not None:
                if i - start >= t: # check sequence for minimum size
                    slices.append((start, i))
                start = None
        i += 1

    # if sequence of 1's doesn't end with -1 within array
    if start is not None:
        if i - start >= t:
            slices.append((start, i))

   return slices

@科琳娜很有趣,所以没问题!
def slices(a, t):
    start = None
    i = 0 # index into array
    slices = [] 
    for val in a:
        if a[i] == 1: # start of sequence
            if start is None:
                start = i
        else: # -1 end of sequence
            if start is not None:
                if i - start >= t: # check sequence for minimum size
                    slices.append((start, i))
                start = None
        i += 1

    # if sequence of 1's doesn't end with -1 within array
    if start is not None:
        if i - start >= t:
            slices.append((start, i))

   return slices