Delete items from the list if they are within a given range

advertisements

I want to remove every item from a sorted list, when it is within 100 seconds from one of the previous events. Example:

event_list = [3, 10, 12, 140, 140, 150, 300]
filtered_event_list = [3, 140, 300]

I have the following piece of code that seems to work. But it does not remove an item that has the same time as the previous one. Another problem Ihave is that it is not very pythonic since I need an additional placeholder for true/false or 0/1 to store my result before I start removing the items that are within 100 seconds.

downCycles = 100
event_list = [[3, 0], [10, 0], [12, 0], [140, 0], [140, 0], [150, 0], [300, 0]]

for e_idx, event in enumerate(event_list):

if e_idx > 0:

    prev_idx = e_idx - 1

    while event[0] - event_list[prev_idx][0] < downCycles and prev_idx >= 0:

        event[1]  = event[0] - event_list[prev_idx][0]
        prev_idx -= 1

filtered_event_list = [e for e in event_list if e[1] == 0]
# filtered_event_list = [[3, 0], [140, 0], [140, 0], [300, 0], [800, 0]]

Has anybody an idea for removing the second 140 in this example? Has anybody a better way to write this piece of code?

Thanks Regards Michael


This returns a generator which contains the items.

def removeCloseItems(items, itemDistance):
    if items:
        lastOutput = items[0]
        yield items[0]
        for currentItem in items[1:]:
            if ((currentItem - lastOutput) > itemDistance):
                lastOutput = currentItem
                yield currentItem

Sample usage:

In [79]: [x for x in removeCloseItems ([3, 10, 12, 140, 140, 150, 300], 100)]
Out[79]: [3, 140, 300]

This assumes that when you say "within 100 from one of the previous items", you mean one of the previous output items. What should the output be for this:

[x for x in removeCloseItems([1, 100, 102], 100)

Do you want [1, 102], or [1]?

The latter would be generated with this code:

def removeCloseItems(items, howFar):
    if items:
        lastItem = items[0]
        yield items[0]
        for currentItem in items[1:]:
            lastItem = currentItem
            if ((currentItem - lastItem) > howFar):
                yield currentItem