首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在由1和0组成的python数组中找到1s组的中间点的最佳方法是什么?

在由1和0组成的python数组中找到1s组的中间点的最佳方法是什么?
EN

Stack Overflow用户
提问于 2021-05-17 13:32:54
回答 3查看 69关注 0票数 0

我有包含0和1的数组。我想找出每个连续的1s组的中间点的索引。例:array = [0,0,0,1,1,1,0,0,1,1,1,1,1,0,0]

然后从每个连续的1s组中,中间1s的索引为

4 -> from first group

10 -> from second group

在python中找到这些索引的最佳方法是什么?(在实际场景中,这些数组包含大约1000个元素。所以我正在寻找一个有效的答案)

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-05-17 15:27:25

下面是一个提高速度的解决方案:

代码语言:javascript
运行
复制
import numpy as np
array = [1,0,0,0,1,1,1,0,0,1,1,1,1,1,1,0,0,1]

#padding the array with 0 to ensure that first and last elements are not neglected 
arr = np.asarray([0] + array + [0])
#finding borders between 0 and 1
arr_diff = np.diff(arr)
#finding index values of first and last elements of each group of 1's
first = np.where(arr_diff == 1)[0]
last = np.where(arr_diff == -1)[0] - 1
#calculate the mean value of these indexes
ind = np.ceil(np.mean([first, last], axis=0)).astype(int)
print(ind)

样本输出:

代码语言:javascript
运行
复制
[ 0  5 12 17]
票数 2
EN

Stack Overflow用户

发布于 2021-05-17 13:42:44

只需对列表进行迭代:

代码语言:javascript
运行
复制
def middlePoints(list):
    ones = False
    start = -1
    end = -1
    middle = []
    for index, item in enumerate([0] + list + [0]):
        if item == 1 and not ones:
            ones = True
            start = index - 1
        elif item == 0 and ones:
            ones = False
            end = index - 2
            middle.append((start + end) / 2)
            start = -1
            end = -1
    return middle

print(middlePoints([0,0,0,1,1,1,0,0,1,1,1,1,1,0,0])) # [4.0, 10.0]
print(middlePoints([0,0,0,1,1,1,0,0,1,1,1,1,0,0,0])) # [4.0, 9.5]

这个解很简单,但是在线性时间O(n)中工作,所以我怀疑你会发现更快/更好的东西。

注:在这里,如果1s组为偶数,则中间索引将为浮动(例如5.5 )。

票数 1
EN

Stack Overflow用户

发布于 2021-05-17 13:52:20

下面是一个找到中间点的简单算法:

代码语言:javascript
运行
复制
array = [0,0,0,1,1,1,0,0,1,1,1,1,1,0,0]

def middle_points(array):
    indexes = []
    first_one = -1
    for i in range(len(array)):
        if first_one == -1 and array[i] == 1:
            first_one = i 
        elif first_one > -1 and array[i] == 0:
            indexes.append((first_one+i-1)//2)
            first_one = -1
    if first_one > -1: 
        indexes.append((first_one+len(array)-1)//2)
    return indexes

print(middle_points(array)) #[4, 10]

该算法与输入的大小成线性关系,具有很高的效率。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67570742

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档