Python lambda function underscore-colon syntax explanation?

后端 未结 3 1254
失恋的感觉
失恋的感觉 2021-01-23 19:31

In the following Python script where \"aDict\" is a dictionary, what does \"_: _[0]\" do in the lambda function?

sorted(aDict.items(), key=lambda _: _[0])
         


        
3条回答
  •  不知归路
    2021-01-23 20:07

    In Python _ (underscore) is a valid identifier and can be used as a variable name, e.g.

    >>> _ = 10
    >>> print(_)
    10
    

    It can therefore also be used as the name of an argument to a lambda expression - which is like an unnamed function.

    In your example sorted() passes tuples produced by aDict.items() to its key function. The key function returns the first element of that tuple which sorted() then uses as the key, i.e that value to be compared with other values to determine the order.

    Note that, in this case, the same result can be produced without a key function because tuples are naturally sorted according to the first element, then the second element, etc. So

    sorted(aDict.items())
    

    will produce the same result. Because dictionaries can not contain duplicate keys, the first element of each tuple is unique, so the second element is never considered when sorting.

提交回复
热议问题