Reputation: 2167
How could I convert the following line of code using a lambda command into a function by itself?
I am struggling to get the hang of lambda, and wanted to apply it to an example I found. I am confused about how to convert the x
and y
when I put it in it's own function, like def sortedList(myList)
The line with the lambda is as follows:
myList = [[1,2],[19,20],[2,3]]
listNums = sorted(myList,
sortList = lambda x,y: x[0] + y[0] if x[0] == y[0] else y[1] - x[1])
Upvotes: 0
Views: 71
Reputation: 9977
listNums = sorted(myList,
sortList = lambda x,y: x[0] + y[0] if x[0] == y[0] else y[1] - x[1])
is equivalent to
def funcname(x,y):
return x[0] + y[0] if x[0] == y[0] else y[1] - x[1]
listNums = sorted(myList, sortList=funcname)
However, that is not the correct syntax for sorted
- it should be
listNums = sorted(mylist, cmp=funcname)
To address your comment, sorted uses the cmp
function to sort the elements of your list. In your question, your list is
[[1,2],[19,20],[2,3]]
. The basic question is, which comes first [1,2]
or [19,20]
? Because that question could be answered nearly infinite different ways, it lets you provide the answer with a cmp function. In that case, to decide which of those pairs comes first, sorted will run cmp(x=[1,2], y=[19,20])
. If the value is > 0, it assumes x is higher, if it is < 0 it considers y as higher, and if the return value is 0 it figures they are the same value.
The example you chose seems a weird way to do comparisons... if the first values are equal, return the sum of the first values? If they are both positive, then x will always be higher, if they are both negative, y will always be higher. If they aren't equal, sort solely based on the second value.
Upvotes: 1