找到最长连续数字序列的长度

时间:2013-05-24 10:47:57

标签: python numpy

我有一个像这样的numpy数组[1,1,1,-1,-1,1,-1,1,1,-1,-1,-1,1,-1]我想找到最长的1s或-1s连续系列的长度。在示例中,它应该是3

2 个答案:

答案 0 :(得分:17)

纯Python

>>> from itertools import groupby
>>> L = [1,1,1,-1,-1,1,-1,1,1,-1,-1,-1,1,-1]
>>> max(sum(1 for i in g) for k,g in groupby(L))
3

答案 1 :(得分:5)

@AlexMartelli

的回答类似
>>> import numpy as np
>>> nums = np.array([1,1,1,-1-1,1,-1,1,1,-1,-1,-1,1,-1])
>>> run_ends = np.where(np.diff(nums))[0] + 1
>>> np.diff(np.hstack((0, run_ends, nums.size))).max()
3