简体   繁体   中英

Delete elements in list that are closer than N from each other

Let's suppose I have the following list:

a = [0,5,10,11,15,22]

...and I want to make sure that the list elements are always a minimum of 5 apart from each other, how could I do that?

expected result:

[0,5,10,15,22]

What I tried is not very pythonic:

a.sort()
prev_elem = a[0]
new_list = []
for elem in a[1:]:
    if abs(prev_elem-elem) >= 5:
         new_list.append(prev_elem)
    # update
    prev_elem = elem

EDIT: BEFORE YOU DOWNVOTE : Why are you downvoting? Please add a comment? I am asking a question and I have shown my work, so there is no reason to downvote.

You can do it with a few very small changes to your existing code.

Lines that are changed are commented below.

a = [0,5,10,11,15,22]

a.sort()
prev_elem = a[0]
new_list = [prev_elem]  # <====== initialise with one element
for elem in a[1:]:
    if abs(prev_elem-elem) >= 5:
         new_list.append(elem)  # <===== append the new element
         prev_elem = elem  # <===== indented more (inside "if" block)

print(new_list)

This gives:

[0, 5, 10, 15, 22]

Iterate through the list. If arr[i]+5 >arr[i+1], then delete arr[i+1]. Something like the following code.

i = 0
while i < len(arr)-1:
    if arr[i]+5 > arr[i+1]:
        del arr[i+1]
    else:
        i+=1

There's definitely cleaner and more efficient ways to do this, but this should work.

Note this is pseudo code where n is the length of the array named arr:

for i = 1 to n
    if (arr[i] - arr[i - 1] >= 5 OR arr[i] - arr[i - 1] <= -5)
        //remove arr[i]

One way of doing it:

a = [0,5,10,11,15,22]
result = []

for i, num in enumerate(a):
    if i == 0:
        result.append(num)
        continue
    if 3 <= abs(num - a[i-1]):
        result.append(num)

# [0,5,10,11,15,22] -> [0, 5, 10, 15, 22]
# [10, 9, 5, 0] -> [10, 5, 0]
# [10, 14, 9, 11, 5, 7, 0] -> [10, 14, 9, 5, 0]

EDIT:

I realized that it can be done simpler. Using slice and unpacking avoids index error in case of empty list:

result = [*a[0:1]]      

for num in a[1:]:
    if 3 <= abs(num - result[-1]):
        result.append(num)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM