Python sort using key and lambda, what does lambda do?

前端 未结 1 1431
不知归路
不知归路 2021-01-24 20:17

So I have a list of values like so:

{
    \"values\": 
    [
        {
            \"date\": \"2015-04-15T11:15:34\",
            \"val\": 30
        },
                 


        
相关标签:
1条回答
  • 2021-01-24 20:54

    A lambda expression is simply a concise way of writing a function. It's especially handy in cases like the one you give where you only need to use the function once, and it needs to be used as an expression (e.g. an argument to a function).

    Here's an alternative version of your example, using def statement instead of a lambda expression:

    def keyfunc(values):
        return values["date"]
    values.sort(key=keyfunc)
    

    That's two lines longer, and leaves behind an extra variable in the current namespace. If the lambda version is just as clear as the def version, it's generally a better choice.

    It looks like your confusion may come from the extra use of the name values in the function. That's simply a poorly chosen argument name. The list.sort method will call the key function once for each value in the list, passing the value as the first positional argument. That value will be bound to whatever variable name is used in the function declaration (regardless of whether it's a def or a lambda). In your example, a better name might be val or item, since it's going to be just a single item from the values list. The name could really be whatever you want (and indeed, values works fine, it just looks confusing). This would be clearer:

    values.sort(key=lambda val: val["date"])
    

    Or:

    def keyfunc(val):
        return val["date"]
    values.sort(key=keyfunc)
    
    0 讨论(0)
提交回复
热议问题