1

I have a list which contains numbers in ascending order like

[0, 1, 3, 4, 6]

or

[2, 3, 4, 5]

I need to get a list of lists which contains the elements as a range items like

[[start, end], [start, end]] from the input list.

[[0, 1], [3, 4], [6, 6]]

or

[[2, 5]]

where the elements that are not present in the input list should.

Here is the code I tried. But not sure how to get it.

zers = [0, 1, 3, 4, 6]
ls = []
for i, j in enumerate(zers):
    if i!=len(zers)-1 and zers[i+1]==zers[i]+1:last=i;continue
    else:
        if i==0:ls.append([i,i])
        else:ls.append([last, i])
print(ls) 

It is supposed to give [[0, 1], [3, 4], [6, 6]] But giving [[0, 1], [2, 3], [2, 4]]

Please feel free to make any modifications to my code or provide completely different solution.

I'm thinking that there should be a function from an existing library but just not sure. Please let me know if you comes across such.

Underoos
  • 4,708
  • 8
  • 42
  • 85
  • The `enumerate` is adding confusion. The pairs it produces are "index", "value". You're only using the index, and ignoring the values, so it's equivalent to `for i in range(len(zers)):`. – Tom Karzes Jun 10 '19 at 11:18
  • Can I generate a list from `[0, 1, 3, 4, 6]` like `[[0, 3], [4, 6]]`? How do you make a difference? – Shahroozevsky Jun 10 '19 at 11:20
  • [0, 3] is wrong because it doesn't contain 2. – Jean-François Fabre Jun 10 '19 at 11:21
  • @Shahroozevsky Your example is incorrect. Read the post again. For your example, the correct result would be `[[0, 1], [3, 4], [6, 6]]`. Your proposed output implies that `2` is present between `1` and `3`, which it clearly is not. – Tom Karzes Jun 10 '19 at 11:21
  • @Shahroozevsky No. The tuple items should be similar to range. `[Start, End]` All the numbers in that range should be present in the input list. – Underoos Jun 10 '19 at 11:22
  • One problem with the posted code is that `last` isn't always defined when it's used. Consider `[1, 3, 5]`. In this case, `last` will never be defined, but it will try to use it. – Tom Karzes Jun 10 '19 at 11:25

1 Answers1

2

Use more_itertools.consecutive_groups to make group of successive elements and then fetch 1st and last element from the groups:

import more_itertools as mit

iterable = [0, 1, 3, 4, 6]
x = [list(group) for group in mit.consecutive_groups(iterable)]

output = [[i[0],i[-1]] for i in x]
print(output)

Output:

[[0, 1], [3, 4], [6, 6]]
Sociopath
  • 13,068
  • 19
  • 47
  • 75