Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty understanding lambda function in sort

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?

like image 342
Dnaiel Avatar asked Dec 16 '22 13:12

Dnaiel


1 Answers

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.

like image 144
NPE Avatar answered Dec 18 '22 11:12

NPE