I see it used in sorting, but what do the individual components of this line of code actually mean?
key=lambda x: x[1]
What\'s lambda
lambda
signifies an anonymous function. In this case, this function takes the single argument x
and returns x[1]
(i.e. the item at index 1 in x
).
Now, sort(mylist, key=lambda x: x[1])
sorts mylist
based on the value of key
as applied to each element of the list. Similarly, max(gs_clf.grid_scores_, key=lambda x: x[1])
returns the maximum value of gs_clf.grid_scores_
with respect to whatever is returned by key
for each element.
I should also point out that this particular function is already included in one of the libraries: operator. Specifically, operator.itemgetter(1)
is equivalent to your key
.