简体   繁体   中英

Exclude integer values from list that have difference less than 80

I have a list that contains many values like

mylist = [4361, 4868,4878, 5395, 5940, 6539, 6544, 7164 ]

In case I have values that have difference less than 80, like 4868,4878 I want to exclude the second one and keep only 4868 and get the indexes of the those that are deleted.

The new resulted list will be

my_list = [4361, 4868, 5395, 5940, 6539, 7164]

Is there an easy way to achieve this?

Assuming the list is sorted, just compare the current value to the last value in the result list, if any, and append it if the difference is sufficiently large.

mylist = [4361, 4868,4878, 5395, 5940, 6539, 6544, 7164 ]
n = 80
result, deleted = [], []
for i, x in enumerate(mylist):
    if result == [] or x - result[-1] > n:
        result.append(x)
    else:
        deleted.append(i)
print(result)  # [4361, 4868, 5395, 5940, 6539, 7164]
print(deleted) # [2, 6]

This should do the trick:

mylist = [4361, 4868, 4878, 5395, 5940, 6539, 7164]

new = [x for x, y in zip(mylist, mylist[1:]) if y - x >= 80]
if mylist[-1] - new[-2] >= 80:
    new.append(mylist[-1])

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