[Numpy-discussion] List/location of consecutive integers
josef.pktd@gmai...
josef.pktd@gmai...
Fri May 22 11:53:19 CDT 2009
On Fri, May 22, 2009 at 12:31 PM, Andrea Gavana <andrea.gavana@gmail.com> wrote:
> Hi All,
>
> this should be a very easy question but I am trying to make a
> script run as fast as possible, so please bear with me if the solution
> is easy and I just overlooked it.
>
> I have a list of integers, like this one:
>
> indices = [1,2,3,4,5,6,7,8,9,255,256,257,258,10001,10002,10003,10004]
>
> >From this list, I would like to find out which values are consecutive
> and store them in another list of tuples (begin_consecutive,
> end_consecutive) or a simple list: as an example, the previous list
> will become:
>
> new_list = [(1, 9), (255, 258), (10001, 10004)]
>
> I can do it with for loops, but I am trying to speed up a fotran-based
> routine which I wrap with f2py (ideally I would like to do this step
> in Fortran too, so if you have a suggestion on how to do it also in
> Fortran it would be more than welcome). Do you have any suggestions?
>
> Thank you for your time.
>
something along the line of:
>>> indices = np.array([1,2,3,4,5,6,7,8,9,255,256,257,258,10001,10002,10003,10004])
>>> idx = (np.diff(indices) != 1).nonzero()[0]
>>> idx
array([ 8, 12])
>>> idxf = np.hstack((-1,idx,len(indices)-1))
>>> vmin = indices[idxf[:-1]+1]
>>> vmax = indices[idxf[1:]]
>>> zip(vmin,vmax)
[(1, 9), (255, 258), (10001, 10004)]
Josef
More information about the Numpy-discussion
mailing list