Search code examples
pythonpython-itertools

Python: get indices of elements that are in a streak of at least 3?


(this isn't homework, I'm teaching myself)

I have a dictionary (actually a Counter) with some counting numbers (call this n) and how many times that number occured (call this c). i.e.

my_dict = { n0: c0, n1: c1, ... , nx: cx }

I want to convert that to sublists of c's if the n's are sequential. i.e. if

my_dict = { 0: 1, 1: 1, 4: 1, 5: 2, 6: 1 }

I'd like

result = [ [ 1 , 1 ] , [ 1 , 2 , 1 ] ]

I could just use a for loop over the index, but that wouldn't be pythonic. However, at this point I'm using multiple itertools functions and still haven't gotten what I want.

Could I get a suggestion?


Solution

  • A for loop might be the simplest solution; iterating over the keys of the dictionary and whenever the key is not equal to the last key plus 1, starting a new list in the output, otherwise appending to the current list:

    my_dict = { 0: 1, 1: 1, 4: 1, 5: 2, 6: 1 }
    
    l = []
    last = max(my_dict.keys())
    for k, v in my_dict.items():
        if k != last + 1:
            l.append([v])
        else:
            l[-1].append(v)
        last = k
            
    print(l)
    

    Output:

    [[1, 1], [1, 2, 1]]