0

If you have a list that always contains integers in ascending order, for e.g. [10, 11, 12, 40, 41, 42, 43, 50, 52, 60, 61, 62]. Note, this list can be different length.

What is the most efficient way in python to split this list when the numbers are not sequentially in order by an increment of 1.

For the example list I gave, the result would look like this: [(10, 11, 12),(40, 41, 42, 43),(50),(52),(60, 61, 62)] or even better just having the first and last value in each tuple, i.e. [(10, 12),(40, 43),(50),(52),(60, 62)]

EDIT

I've tried this so far:

split_arr = [rand_arr[0]]
for i in range(1,rand_arr.shape[0]-1):
    if rand_arr[i] - rand_arr[i-1] != 1:
        if rand_arr[i-1] not in split_arr:
            split_arr.append(rand_arr[i-1])
        split_arr.append(rand_arr[i])
split_arr.append(rand_arr[-1])
AnarKi
  • 857
  • 1
  • 7
  • 27
  • I don't understand what their increments have to do with splitting? Do you mean you want to group them by their division by 10? What have you tried? – Sayse Oct 04 '19 at 08:42
  • Possible duplicate of [Identify groups of varying continuous numbers in a list](https://stackoverflow.com/questions/39709606/identify-groups-of-varying-continuous-numbers-in-a-list) – FObersteiner Oct 04 '19 at 08:48
  • @Sayse I want to split the integers when they are not continuous, I will add what I tried for splitting so far – AnarKi Oct 04 '19 at 08:50
  • 1
    Possible duplicate of [Identify groups of continuous numbers in a list](https://stackoverflow.com/questions/2154249/identify-groups-of-continuous-numbers-in-a-list) – MegaIng Oct 04 '19 at 08:50
  • @MegaIng: the `mit` solution is even nicer! – FObersteiner Oct 04 '19 at 08:55

0 Answers0