![]() |
translating lambda in function - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: translating lambda in function (/thread-26314.html) |
translating lambda in function - fabs - Apr-28-2020 hello everyone, i am a python beginner and would like to understand a bit more about lambda, how to "read" it and when to use it instead of functions. I am working with a list of points (x,y,z) and using this block of code to sort the list based on the z value: orglst.sort(key=lambda orglst:(orglst.Z,orglst.X,orglst.Y))now, this code works well. It was written by someone else and I cant really understand it because I am not familiar with lambda. I then tried to replace the lambda with a function, so I go a way I am familiar with, but it didnt work. In my mind, I was writing exactly the same instructions: def reorder(list): return: list.Z,list.X,list.Y orglst.sort(key=reorder(orglst))then I tried something else, that also went wrong... newlist = [] for point in orglst: newlist.append(point.Z) sort.orglst(key=newlist)Question 1: why are my alternatives not working? Question 2: why would I use lambda instead of a function anyway? Cheers! RE: translating lambda in function - deanhystad - Apr-28-2020 Your attempts failed mostly because you don't understand what the key function does. The original sort is somewhat confusing because of the way it was written. I will rewrite here and hopefully things will be clearer orglst.sort(key=lambda element:(element.Z,element.X,element.Y))key is a function that is evaluated to get a sorting value. If the sort function wants to know how to order orglist[5] and orglist[9], it passes each to the key function and compares the results. In this example the key function creates a tuple(Z, X, Y). Sort knows how to compare tuples. First Z's are compared, then X and eventually Y if necessary. You could do this with a function: def sort_key(element): return (element.Z,element.X,element.Y) orglst.sort(key=sort_key)Your problem was that you were evaluating a function and passing that as the key. The result of the function is not a function, so sort complains. Lambdas are commonly used as sorting keys because sorting keys are usually throw away functions, only used for doing the sort. Making them a regular function makes the key function look like it does something outside the scope of the sort. In most cases a regular function is a better idea because there is some overhead associated with lambdas. |