Home > OS >  Lambda in sorted in python 3 when one parameter is missing
Lambda in sorted in python 3 when one parameter is missing

Time:08-28

I need to write this code

sorted(labeled_points,key=lambda (point, _): distance(point,new_point))

where distance is just Euclidean distance between vectors. The error message I receive is that it isn't possible in Python 3 - Sublist parameters are not supported in Python 3.x . I tried to replace it with this code

sorted(labeled_points,key=lambda point: distance(point,new_point))

but it seems this isn't working.
I also looked at examples and found that we can make do without lambda, we need to define function

def func(point,new_point):
    return distance(point,new_point)
...
sorted(labeled_points,key=func(new_point))

But this does not seem to be evaluated. So,, how one could write this in Python 3?

CodePudding user response:

Instead of

sorted(labeled_points, key=lambda (point, _): distance(point, new_point))

do

sorted(labeled_points, key=lambda labeled_point: distance(labeled_point[0], new_point))

See the end of PEP 3113's Transition Plan for a similar example (that's the PEP that removed this Python 2 syntax in Python 3).

CodePudding user response:

You have a distance function to get the distance between two arbitrary points. You want to sort based on the distance from a fixed point - one of the parameters will always be the same. You can use functools.partial to create a new function that sets static parameters and use that to generate the sort key.

import math
import functools

def distance(v,w):
    return math.sqrt(sum(((v_i-w_i)*(v_i-w_i) for v_i in v for w_i in w)))

fixed_point = (9,9)
points = [(3,4), (20,6), (1,1), (9,9)]
print(list(sorted(points, key=functools.partial(distance, fixed_point))))
  • Related