简体   繁体   中英

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:
[75]

[78]

[100, 101, 102]

[109]

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

g in your example is the iterable of elements (eg, [75], or [100, 101, 102]). If you only want consecutive number s , it sounds like you're looking to print all g s 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)

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