2 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
這是改編自此答案的一個(gè)選項(xiàng):
def count_consecutive(arr, n):
# pad a with False at both sides for edge cases when array starts or ends with n
d = np.diff(np.concatenate(([False], arr == n, [False])).astype(int))
# subtract indices when value changes from False to True from indices where value changes from True to False
return np.flatnonzero(d == -1) - np.flatnonzero(d == 1)
count_consecutive(a, 5)
# array([2, 1, 3])

TA貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊
如果你沒(méi)問(wèn)題,list那么可以使用 groupby
from itertools import groupby
a=[1,5,5,2,3,6,5,2,5,5,5]
[len(list(v)) for k,v in groupby(a) if k==5]
輸出
[2, 1, 3]
添加回答
舉報(bào)