V22
V22

Reputation: 157

How to remove values from a list that are less than a target value from the previous number

Given a sorted list of increasing numbers, I'm trying to create a new list that only keeps values that are at least 3 greater than the previous number. I have tried some conditional statements, but fail to get the correct format. For example, from

a = [3,4,8,12,14,16]

we would obtain

new_a = [3,8,12,16]

Only 14 would drop out because it is less than 3 away from 12, but keep 16 because it is greater than 3 from 12. Also 4 would drop out. Any help would be appreciated!

Upvotes: 1

Views: 5301

Answers (3)

Abstracted
Abstracted

Reputation: 441

Possibly overkill, but if you end up doing this computation a lot (as well as adding new numbers to the list) you can try subclassing list.

class Newlist(list):
    def __init__(self, *args):
        super(Newlist, self).__init__(*args)
        if len(self) > 0:
            i = 1
            while i<len(self):
                if self.__getitem__(i) < 3+self.__getitem__(i-1):
                    self.remove(self.__getitem__(i))
                i += 1

    def append(self, item):
        if len(self) == 0:
            super(Newlist, self).append(item)
        elif item >= self.__getitem__(-1) + 3:
            super(Newlist, self).append(item)
        else: return

Thus you can initialize a list with

a = Newlist([3, 4, 8, 12, 14, 16])

Which will automatically be shortened to [3, 8, 12, 16]

Also append is overriden to only allow new values that follow your rule. Example: a.append(20) will add 20 to the end of a, but a.append(17) will do nothing.

Upvotes: 0

kushtrimh
kushtrimh

Reputation: 916

a = [3,4,8,12,14,16]
b = a[:1]
last_num = b[0]
for num in a:
    if last_num is not None and last_num + 3 <= num:
        b.append(num)
        last_num = num

print(b)

Upvotes: 0

Tim Hoffmann
Tim Hoffmann

Reputation: 1345

This should do:

new_a = a[:1]
for i in a[1:]:
    if i >= new_a[-1] + 3:
        new_a.append(i)

Upvotes: 5

Related Questions