[Numpy-discussion] List/location of consecutive integers

Christopher Barker Chris.Barker@noaa....
Fri May 22 12:03:05 CDT 2009


Andrea Gavana wrote:
> 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)]

Is this faster?

In [102]: indices = 
np.array([1,2,3,4,5,6,7,8,9,255,256,257,258,10001,10002,10003,10004,sys.maxint])

In [103]: breaks = np.diff(indices) != 1

In [104]: zip(indices[np.r_[True, breaks[:-1]]], indices[breaks])
Out[104]: [(1, 9), (255, 258), (10001, 10004)]



-Chris



-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker@noaa.gov


More information about the Numpy-discussion mailing list