前言
如何从一堆坐标点中筛选出哪些点的坐标数值是相近的呢?不妨参考一下下面的代码.
import math
# 读取txt文件获取坐标点
with open("points.txt", "r") as fp:
data = fp.readlines()
# eval是Python的一个内置函数,这个函数的作用是,返回传入字符串的表达式的结果。
data = list(eval(data[0][1:-1])) # 将读取到的数据转为列表数据类
# 打印数据列表长度
print("待处理的坐标长度:", len(data))
# 坐标处理函数
def pic_pionts(lst):
part_lst = [] # 存放相似坐标
part_lst.append(lst[0])
if len(lst) > 1:
for i in range(1, len(lst)):
"""
isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)方法用于确定两个浮点数的值是否接近
a,b:两个需要比较的浮点数;
rel_tol: 相对于输入值的大小,被认为是“接近”的最大差异;
abs_tol: 无论输入值的大小,被认为“接近”的最大差异"""
if math.isclose(lst[0][0], lst[i][0], abs_tol=30) and math.isclose(lst[0][1], lst[i][1], abs_tol=30): # 设置误差数在30以内
part_lst.append(lst[i])
print("坐标相近的点:", part_lst) # 打印坐标相近的点
print("*"*20)
# 在原坐标列表中去除上一步获得的相近坐标点
tem_next_lst = [y for y in (lst + part_lst) if y not in part_lst]
part_lst = []
pic_pionts(tem_next_lst) # 递归调用
else:
print(lst)
pic_pionts(data)