简体   繁体   中英

obtaining start index and end index of consecutive numbers in array in python

I want the python to give me the list of list from an array. each list should tell starting index and end index in the array in between the number are continuous.

For example if I have an array

d=np.array([0,1,2,4,5,6,9,10,11])

I want to get a list

([0,2],[3,5],[6,8])

The first element [0,2] indicates that elements from 0 to 2 in the array d are continuous. I thought about using recursive function but it does not feel like the python way of doing it.

If for some reason you really don't want to use a simple loop:

start_end = np.diff((np.diff(d) == 1) + 0, prepend=0, append=0)
# Look for where it flips from 1 to 0, or 0 to 1.
start_idx = np.where(flip == 1)
end_idx = np.where(flip == -1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM