我有包含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个元素。所以我正在寻找一个有效的答案)
发布于 2021-05-17 15:27:25
下面是一个提高速度的解决方案:
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)样本输出:
[ 0 5 12 17]发布于 2021-05-17 13:42:44
只需对列表进行迭代:
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 )。
发布于 2021-05-17 13:52:20
下面是一个找到中间点的简单算法:
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]该算法与输入的大小成线性关系,具有很高的效率。
https://stackoverflow.com/questions/67570742
复制相似问题