Let's say I define a list of lists lol
:
lol = [['malasia', 0.02, 56.3], ['chile', 0.03, 34.9],
['hungria', 0.01, 45.9], ['ahumada', 0.001, 1]]
Then,
lol.sort(lambda x, y: cmp(y[2], x[2]))
orders lol
by the last element of each sublist...
I'm just trying to understand the component parts of the sort
:
cmp(y,x)
compares to numbers and returns-1
(y less x),0
(x equals y), or1
(y bigger x).lambda
is defining a function over the last elements of each list? Then lambda inside a sort? I'm confused- could anybody explain what the lambda function does?
The lambda function in your example determines which item comes first.
In a "classical"-situation it would simply calculate
x-y
: if the result isnegative
it means thatx is smaller
then y and therefore comesbefore y
.Additionally you may pass a reverse-parameter to the sort-method, which would
reverse=True
the order.Your "sort"-function is in this case the cmp-function in the "lambda-wrapper". Therein you swap the order of x with y and use the 3rd argument, which means it sorts in a reversed order(x/y-swap) and does it by comparing all the 3rd arguments(
x[2]
).Regarding your 2nd bullet:
If your asking what a lambda-function is: It's an anonymous light-weight inline function. Anonymous means it doesn't have an identifier. (But you could assign one. e.g.:
sqr = lambda x : x**2
which you could use now like any other function:y = sqr(2)
)Your example of the sort-function use is a typical use-case for lambda-functions. They are used as "throw-away" functions, which you may inline without to create a own normal function.
A more "pythonic" variation would be something like:
lambda is of type "function"
So your
is equal to
The
sort
takes a function, and when it need to compare two elements, it would call that lambda function, which would return the value ofcmp(y[2], x[2])
So this sort would sort your list in this way: whenever it meets two element, it would fetch the last values in the "triples" and compare them to determine the precedence.
This is actually better done using the
key
argument tosort
,cmp
is somewhat outdated.For example:
(you could also use x[-1] to mean the last element of the list)
You are creating the lambda and passing it into the
sort
function. You could also write it like this:Or to make it even easier to understand:
There's no reason you can't pass a function into another function as an argument!
Basically, when
sort()
needs to compare two elements, it calls the lambda function and uses its result to determine which of the two elements should come first. This is all there is to it.