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

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

    From a reference for Python 3.7 (https://docs.python.org/3/howto/sorting.html), The key is a parameter of list.sort() and sorted(). The first built-in function modifies a list in place while the latter accepts and return iterable.

    The key parameter can be defined as a function to be called on each element of list/iterable before comparison and sort, respectively. In this case, the inline function lambda x: x[1] is defined as a value of the key parameter. The lambda function takes input x return x[1] which is the second element of x.

    Supposed

    mylist = [[7, 8], [1, 2, 3], [2, 5, 6]]
    # list(map(lambda x: x[1], mylist)) returns [8, 2 ,5]
    
    mylistSort = sorted(mylist, key = lambda x: x[1])
    # will sort the nested list based on the result of the lambda function 
    

    Can you guess what the result? mylistSort is then [[1,2,3], [2,5,6], [7,8]] from the sorted sequence of [8,2,5] which is [2,5,8].

    The max() in your example is applied to just get the max value from the outcome of the sort function.

    I hope this post is helpful.

提交回复
热议问题