Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lambda in Python

Tags:

python

sorting

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))  
like image 231
James Carter Avatar asked Jan 31 '13 22:01

James Carter


People also ask

How do you use lambdas in Python?

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).

When lambda is used in Python?

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.

Should I use lambdas 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.).

What is lambda function in Python give example?

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.


1 Answers

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

like image 160
Kyle Strand Avatar answered Sep 26 '22 15:09

Kyle Strand