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), or 1
(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?
Then lambda inside a sort? I am lost!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With