获取两个列表中数值最接近的元素:
在处理数据中,经常需要匹配两个数据集合,找到最接近的那两个元素。
例如:
在处理pcd点云数据和图像的时候,需要在点云和图像两个集合中找到时间戳相对应的那一帧数据
def pcd_match_img(pcd_path, img_path):
pcd_file = os.listdir(pcd_path)
img_file = os.listdir(img_path)
for pcd in pcd_file:
pcd_prefix = os.path.splitext(pcd)[0]
dict = {k:eval(pcd_prefix) - eval(os.path.splitext(k)[0] for k in img_file}
value = 0
img_key, diff_val = min(dict.items(), key=lambda x: abs(value - x[1]))
src_img = os.path.jion(src_path, "jpg", img_key)
new_img_path = src_path + "/img_new"
if not os.path.exists(new_img_path):
os.makedirs(new_img_path)
new_img = os.path.jion(new_img_path, pcd_prefix + ".jpg")
shutil.copyfile(src_img, new_img)