Rico Rico - 6 months ago 28
Python Question

How to choose only consecutive numbers from a list using python

I did research and tried the code below. It almost works but I only want the consecutive numbers in the result. That would be [100,101,102]. I do not want the [75], [78], [109] in the result.

from operator import itemgetter
from itertools import groupby
data = [75, 78, 100, 101, 102, 109]
for k, g in groupby(enumerate(data), lambda (i,x):i-x):
print map(itemgetter(1), g)

The print out from above is:



[100, 101, 102]


What can I do to just get [100, 101, 102]?


g in your example is the iterable of elements (e.g., [75], or [100, 101, 102]). If you only want consecutive numbers, it sounds like you're looking to print all gs where there are greater than one elements in g [Note, g is actually an iterable, but we can quickly convert it to a list with list() for a trivial amount of elements. We'll just need to save the contents, because an element can't be read twice from an iterator]

Try wrapping the print map(itemgetter(1), g) in an if statement, such as:

x = list(g)
if len(x) > 1:
    print map(itemgetter(1), x)