Skip to content
Advertisement

For every consecutive number

I have a list containing data such as [2, 3, 9, 10, 16, 17, 23, 24, 99, 112, 113, 114, 299] and what I would is that, for every set of consecutive numbers, construct a dictionary with the key representing the set of consecutive numbers starting from 1, and the value the consecutive numbers.

The expected output should look like this:

{1: [2, 3], 2: [9, 10], 3: [16, 17], 4: [23, 24], 5: [99], 6: [112, 113, 114], 7: [299]}

Is there an efficient way of doing this?

Advertisement

Answer

The following code will do what you want:

def splitCons(lst):
    retlst = {}

    # Keep empty dict unless there are items.

    if len(lst) > 0:
        # Populate first keyed item with first element.

        key = 1
        retlst = {key:[lst[0]]}

        # Process other elements.

        for num in lst[1:]:
            # Consecutive to previous? Add to existing. Otherwise, add to new.

            if num == retlst[key][-1] + 1:
                retlst[key].append(num)
            else:
                key += 1
                retlst[key] = [num]

    return retlst

print(splitCons([2, 3, 9, 10, 16, 17, 23, 24, 99, 112, 113, 114, 299]))

It simply creates the dictionary and either adds elements to the current last key (if consecutive) or starts a new key (if not).

Output for the test data in the given script (slightly modified to show correct operation where sets are not always pairs), and formatted for readability:

{
    1: [2, 3],
    2: [9, 10],
    3: [16, 17],
    4: [23, 24],
    5: [99],
    6: [112, 113, 114],
    7: [299]
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement