Lorenz Lorenz - 3 months ago 7
Python Question

How to find consecutive/successive objects in a list of objects

I have a list of object that have attributes serial number (SN) and datetime along with others. From how the list is generated, the objects should be in chronological order.
Cronologically, objects can have the following SN:

1,1,1,1,1,2,2,2,3,3,3,3,3,3,2,2,1,2,2,2,2,3,3,1,1,1,3,...

How can I retrive the first an last timestamps of all consecutive sequences of SN. For example for SN=1 that would be the first to fith timestamp as well as the 17th and 24th to 26th.
Same for all SNs that appear in the list of objects.
What I want to go for is a Gantt like Diagram to show at which times these SNs were present.

Answer

If I understand your question correctly, maybe you are looking for something like this?

def consecutive(nums, sn):
    count = {nums[0]: [[0]]}
    for idx, num in enumerate(nums[1:]):
        if num == nums[idx]:
            try:
                count[num][-1][1] = idx + 1
            except IndexError:
                count[num][-1].append(idx + 1)
        else:
            try:
                count[nums[idx]][-1][1] = idx + 1
            except IndexError:
                count[nums[idx]][-1].append(idx + 1)
            try:
                count[num].append([idx + 1])
            except KeyError:
                count[num] = [[idx + 1]]
    return count[sn]

test:

test = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 2, 2, 1, 2, 2, 2, 2, 3, 3, 1, 1, 1, 3]
print consecutive(test, 3) # will return [[8, 14], [21, 23], [26]], which are the index ranges for SN = 3