I am trying to use lambda do to some sorting on a list. What I wanted to do is sort the coordinates based on their manhattan distance from an inital poisition. I know I have most of the syntax down but it seems like I am missing something small, Thanks!
while (len(queue) > 0):
queue.sort(queue, lambda x: util.manhattanDistance(curr,x))
Syntax. Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).
Python Lambda Functions are anonymous function means that the function is without a name. As we already know that the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python.
One of the foremost common use cases for lambdas is in functional programming as Python supports a paradigm (or style) of programming referred to as functional programming. It allows you to supply a function as a parameter to a different function (for example, in map, filter, etc.).
Example of Lambda Function in python Here is an example of lambda function that doubles the input value. In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 is the expression that gets evaluated and returned.
It appears that you're trying to tell the sort()
method to use your lambda function as the key for sorting. This is done with the keyword argument key
:
queue.sort(queue, key = [your lambda function])
The rewritten line is:
queue.sort(queue, key = lambda x: util.manhattanDistance(curr,x))
EDIT: misunderstood the purpose of the original lambda function; thought it was intended as a comparison function, which doesn't make sense since distance functions can't be negative
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With