What does this mean: key=lambda x: x[1] ?

前端 未结 6 2019
离开以前
离开以前 2021-02-05 06:17

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

6条回答
  •  既然无缘
    2021-02-05 07:01

    lambda effectively creates an inline function. For example, you can rewrite this example:

    max(gs_clf.grid_scores_, key=lambda x: x[1])
    

    Using a named function:

    def element_1(x):
        return x[1]
    
    max(gs_clf.grid_scores_, key=element_1)
    

    In this case, max() will return the element in that array whose second element (x[1]) is larger than all of the other elements' second elements. Another way of phrasing it is as the function call implies: return the max element, using x[1] as the key.

提交回复
热议问题