I am having trouble with the lambda function and not really understanding it completely. I am trying to calculate the manhattan distance between two points, 1 point is the current location and the second point is from a list that contains multiple positions. Any help is appreciated, thank you
my function is:
toVisit.sort(toVisit,key = lambda x: util.manhattanDistance(curr,x))
I am trying to get a value out of the toVisit list but don’t know how to exactly. I was thinking of passing in x with the curr location but that does not work.
Look at the documentation (or built-in help, or how-to. The signature for
list.sortis:The notes explain, among other things, what each of those parameters mean. In particular, the first parameter,
cmp:You’re passing
toVisitas the first argument. So,toVisitwill be used as a comparison function. You can’t possibly have thought that was what you wanted. So, I’m guessing you probably don’t get the basics of objects and dot notation, and you need to read an appropriate tutorial. (Sorry, I don’t have one to recommend. I checked the official Python tutorial, but it seems to assume that dot notation, and what a method is, and so on are all just obvious and need no explanation…)Here’s the right version:
Meanwhile, there doesn’t seem to be any problem with the
lambdafunction itself, but you seem to be convinced, in two questions in a row, that thelambdais the part you’re having trouble with. If you ever have trouble with alambda, the easiest thing to do is transform it into a normal named function, which is trivial to do.Where you have this:
Do this a line above it:
Then, replace the
lambda ARGS: EXPRwithgood_name_for_what_expr_does.So, this is equivalent to your original code:
Can you see the problem there any more easily than in the
lambdaversion?