pythonmatplotlib

python list remove too near numbers


I want to use a list as matplotlib ticks, but if the ticks too near, it will be overlapped each other.

So it's better to remove too near numbers. for example:

distance = 10

x = [1,2,3,20,21,23,30,40,50]

f(x) = [1,20,30,40,50]

What's the best way to get such a result?


Solution

  • You can loop the list to verify that:

    x = [1, 2, 3, 20, 21, 23, 30, 40, 50]
    distance = 5
    for index in range(len(x)-1, 0, -1):
        if (x[index] - distance <= x[index-1]):
            x.remove(x[index])
    print(x)
    

    you can change the distance according to your preference, hope that helped