Python lambda function underscore-colon syntax explanation?

后端 未结 3 1207
失恋的感觉
失恋的感觉 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:34

    In Python, lambda is used to create an anonymous function. The first underscore in your example is simply the argument to the lambda function. After the colon (i.e. function signature), the _[0] retrieves the first element of the variable _.

    Admittedly, this can be confusing; the lambda component of your example could be re-written as lambda x: x[0] with the same result. Conventionally, though, underscore variable names in Python are used for "throwaway variables". In this case, it implies that the only thing we care about in each dictionary item is the key. Nuanced to a fault, perhaps.

提交回复
热议问题