Python 获取numpy数组中具有最小长度的相同项序列的范围
考虑一个数组,其中的条目完全由-1或1组成。如何获取包含1且最小长度为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)]一种使用和的方法- 我
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