5

I have a list of integers, and I want to generate a list containing a list of all the continuous integers.

#I have:
full_list = [0,1,2,3,10,11,12,59]
#I want:
continuous_integers = [[0,1,2,3], [10,11,12], [59]]

I have the following which works, but seems like a poor way to do it:

sub_list = []
continuous_list = []
for x in full_list:
    if sub_list == []:
        sub_list.append(x)
    elif x-1 in sub_list:
        sub_list.append(x)
    else:
        continuous_list.append(sub_list)
        sub_list = [x]
continuous_list.append(sub_list)

I've seen other questions suggesting that itertools.groupby is an efficient way to do this, but I'm not familiar with that function and I seem to be having trouble with writing a lambda function to describe the continuous nature.

Question: Is there a better way to be doing this (possibly with itertools.groupby?)

Considerations: full_list will have between 1 and 59 integers, will always be sorted, and integers will be between 0 and 59.

ded
  • 420
  • 2
  • 13

1 Answers1

10

You can use the following recipe:

from operator import itemgetter
from itertools import groupby
full_list = [0,1,2,3,10,11,12,59]
cont = [map(itemgetter(1), g) for k, g in groupby(enumerate(full_list), lambda (i,x):i-x)]
# [[0, 1, 2, 3], [10, 11, 12], [59]]
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • 2
    Usually when I say something is clever, I mean it as a criticism: by "clever" I mean "depends upon a non-obvious feature of a problem in a subtle way which isn't robust or generally useful". This, however, is clever in a good way. – DSM Mar 07 '13 at 16:26
  • @DSM It use to be a recipe in the `itertools` documentation - but can't seem to find it there anymore... – Jon Clements Mar 07 '13 at 17:02
  • +1: what @DSM said. [Here's a link to consecutive runs example in the docs](http://docs.python.org/2.6/library/itertools.html#examples) – jfs Mar 07 '13 at 18:51
  • @J.F.Sebastian thanks for posting the link - knew I wasn't imagining it ;) – Jon Clements Mar 07 '13 at 18:55