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

前端 未结 6 2021
离开以前
离开以前 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:12

    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.

提交回复
热议问题