gpt4 book ai didi

python - 在numpy数组中获取具有最小长度的相同条目的序列范围

转载 作者:太空狗 更新时间:2023-10-30 01:21:12 25 4
gpt4 key购买 nike

考虑一个数组,其条目仅由 -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)]

最佳答案

一种使用 np.diff 的方法和 np.where -

# Append with `-1s` at either ends and get the differentiation
dfa = np.diff(np.hstack((-1,a,-1)))

# Get the positions of starts and stops of 1s in `a`
starts = np.where(dfa==2)[0]
stops = np.where(dfa==-2)[0]

# Get valid mask for pairs from starts and stops being of at least 3 in length
valid_mask = (stops - starts) >= 3

# Finally collect the valid pairs as the output
out = np.column_stack((starts,stops))[valid_mask].tolist()

关于python - 在numpy数组中获取具有最小长度的相同条目的序列范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33255960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com