You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

高效定位数组中排除首尾的连续0的中间索引

问题需求

给定一个由非负数组成的数组,需定位数组中每组连续0的中间0的索引,但需排除数组首尾的连续0。

示例数组:

np.array([0, 0, 0, 1, 2, 0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 5, 6, 0, 0, 0])

期望返回索引6和13(当连续0的数量为偶数时,取floor或ceil均可)。

现有可行实现

当前已实现如下可正常运行的代码:

def middle_zero(array):
    busy = False
    not_start_zero = False

    middle_zero_list = []

    for i in range(len(array)):
        if array[i] > 0:
            not_start_zero = True

        if array[i] == 0 and not_start_zero and not busy:
            start = i
            busy = True
        if busy and array[i] > 0:
            end = i
            middle_zero_list.append(int(np.mean([start, end])))
            busy = False

    return np.array(middle_zero_list)

调用示例:

middle_zero(np.array([0, 0, 0, 1, 2, 0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 5, 6, 0, 0, 0]))
>> array([6, 13])
优化需求

该实现可正常运行,但因需多次执行该计算,现寻求更高效的优化方案。

内容的提问来源于stack exchange,提问作者TheEreStack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 09:24:20