pythonlistsequencedrop

Drop numbers in list with condition in python


I am trying to drop numbers located between consecutive numbers in list. Example:

Form

[1, 3, 5, 6, 7, 8, 9, 11, 12, 13, 18]

To

[1, 3, 5, 9, 11, 13, 18]

You'll see that [6, 7, 8] and [12] are dropped


Solution

  • You can try itertools.groupby:

    from itertools import groupby
    
    lst = [1, 3, 5, 6, 7, 8, 9, 11, 12, 13, 18]
    
    out = []
    for _, g in groupby(enumerate(lst), lambda k: k[0] - k[1]):
        g = list(g)
        out.append(g[0][1])
        if len(g) > 1:
            out.append(g[-1][1])
    
    print(out)
    

    Prints:

    [1, 3, 5, 9, 11, 13, 18]