首页 > 解决方案 > python list删除太近的数字

问题描述

我想使用一个列表作为 matplotlib 刻度,但是如果刻度太近,它将相互重叠。

所以最好去掉太接近的数字。例如:

distance = 10

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

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

获得这种结果的最佳方法是什么?

标签: pythonmatplotlib

解决方案


您可以循环列表以验证:

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)

您可以根据自己的喜好更改距离,希望对您有所帮助


推荐阅读