Python 3中sorted函数含缺失参数的Lambda表达式改写问题
解决Python 3中sorted函数的lambda元组参数问题
原来的Python 2写法里,lambda (point, _): ...这种元组解包的参数形式在Python 3里已经被移除,因此会触发报错。下面是正确写法及对错误写法的分析:
正确的简洁写法
直接将lambda的参数视为完整元组,通过索引取出需要的point向量即可:
sorted(labeled_points, key=lambda item: distance(item[0], new_point))
这里item对应labeled_points中的每个元素(即(point, 标签)形式的元组),item[0]就是用于计算距离的目标向量。
你之前写法的问题分析
错误的lambda替换:
你写的lambda point: distance(point, new_point)中,point实际接收的是整个(point, 标签)元组,而非单独的向量,导致distance函数拿到错误的参数类型,无法正确计算欧氏距离。自定义函数的问题:
sorted的key参数需要一个仅接收单个参数的函数(该参数为待排序列表中的每个元素)。你直接调用func(new_point)会立刻执行函数,而非传入函数对象,因此报错。如果想用自定义函数,可以通过闭包绑定new_point:def key_func(new_point): def inner(item): return distance(item[0], new_point) return inner # 调用方式 sorted(labeled_points, key=key_func(new_point))或者用
functools.partial包装函数:from functools import partial def calculate_distance(item, new_point): return distance(item[0], new_point) sorted(labeled_points, key=partial(calculate_distance, new_point=new_point))
内容的提问来源于stack exchange,提问作者Strongscientist
相关产品推荐
相关产品推荐

