Why does max behave differently if I pass a lambda as key compared to applying it directly to a map of the original iterable with the same lambda?

后端 未结 1 791
北恋
北恋 2021-01-29 13:13

I\'m trying to understand how the key argument works in the max function, coming from a problem of finding the closest integer to 0 from a list, and using the positive value in

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-29 13:41

    You are comparing two different things.

    For your first case, if we look at the docs: https://docs.python.org/3/library/functions.html#max

    max(arg1, arg2, *args[, key])
    Return the largest item in an iterable or the largest of two or more arguments. The key argument specifies a one-argument ordering function like that used for list.sort().

    Which means that the key lambda x: (-abs(x), x) is a ordering function, which means that for every x in iterable a, (-abs(x), x) is evaluated and is used to order the items for finding out the maximum element of the iterator, and according to that ordering, 1 is the maximum element

    In [24]: a = [1,4,6,-8,-10] 
    
    In [40]: print(max(a, key=lambda x: (-abs(x), x), default=0))                                                                                                                       
    1
    

    For the second case, if we look at the docs: https://docs.python.org/3/library/functions.html#map

    map(function, iterable, ...)
    Return an iterator that applies function to every item of iterable, yielding the results

    Which means that the function lambda x: (-abs(x), x) is applied to every element x of a, so we get back (-abs(x), x) for every x, and the max is applied on the updated iterator, which is the largest tuple (-1,1)

    In [25]: b = list(map(lambda x: (-abs(x), x), a))  
    
    In [26]: b                                                                                                                                                                          
    Out[26]: [(-1, 1), (-4, 4), (-6, 6), (-8, -8), (-10, -10)]
    
    In [27]: max(b)                                                                                                                                                                     
    Out[27]: (-1, 1)
    

    0 讨论(0)
提交回复
热议问题