如何从tuple组成的list中返回首元素最接近指定值的配对的另一个值
实现方法
小数据量场景(推荐,代码简洁)
直接使用Python内置的min()函数,通过自定义key计算tuple首元素和目标值的差值绝对值,即可快速找到符合要求的tuple:
# 示例数据 data = [(78, 10), (84, 11), (75, 12), (78, 13), (75, 14), (77, 15), (79, 16), (81, 17), (83, 18), (85, 19)] def get_second_val_by_closest_first(tuple_list, target_num): # key指定为每个tuple首元素和目标值的差值绝对值,min会自动匹配最小差值的tuple closest_tuple = min(tuple_list, key=lambda item: abs(item[0] - target_num)) return closest_tuple[1] # 测试 print(get_second_val_by_closest_first(data, 79)) # 输出结果:16
大数据量高频查询场景
如果数据量超过10万条且需要多次查询,建议先对首元素排序后用二分查找优化性能,时间复杂度可从O(n)降到O(logn):
import bisect def get_second_val_by_closest_first_big(tuple_list, target_num): # 先按首元素对tuple列表排序 sorted_list = sorted(tuple_list, key=lambda x: x[0]) sorted_first_vals = [item[0] for item in sorted_list] # 用二分查找定位插入位置 insert_pos = bisect.bisect_left(sorted_first_vals, target_num) # 处理边界情况 if insert_pos == 0: return sorted_list[0][1] if insert_pos == len(sorted_list): return sorted_list[-1][1] # 比较前后两个元素的差值,取更接近的 prev_val = sorted_first_vals[insert_pos - 1] curr_val = sorted_first_vals[insert_pos] if curr_val - target_num < target_num - prev_val: return sorted_list[insert_pos][1] else: return sorted_list[insert_pos - 1][1]
特殊情况说明
如果存在多个tuple首元素和目标值的差值完全相同,默认返回列表中第一个出现的tuple的第二个元素,如有去重、返回全部等特殊需求,可在拿到匹配tuple后额外加逻辑处理。
内容的提问来源于stack exchange,提问作者pete2213
相关产品推荐
相关产品推荐

