Python beginner - Sorting tuples using lambda functions

后端 未结 3 1617
生来不讨喜
生来不讨喜 2021-01-15 03:05

I\'m going through the tutorial intro for Python and I\'m stuck on understanding a piece of code. This is from section 4.7.5 of the tutorial.

pairs = [(1, \'         


        
3条回答
  •  旧时难觅i
    2021-01-15 03:27

    A lambda is a simplified function, using only an expression.

    Any lambda can be written as a function, by adding in a return before the expression, so lambda pair: pair[1] becomes:

    def lambda_function(pair): return pair[1]
    

    So the lambda in the list.sort() call here returns the second element of each sequence that is passed in (Python indexes start at 0).

    You can make this visible by assigning the lambda to a variable, say, key:

    >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
    >>> key = lambda pair: pair[1]
    >>> key(pairs[0])
    'one'
    >>> key(pairs[1])
    'two'
    

    The list.sort() method uses the output of these calls (once for each element in the list) to sort the elements. So for the 4 elements, the function returns 'one', 'two', 'three', and 'four', and the 4 tuples are then sorted purely on the lexicographical (alphabetical) ordering of those 4 strings. That order would be 'four', 'one', 'three', 'two', which is what you see reflected in the final sorted list.

    This form of sorting-by-alternative-key is commonly called a Schwartzian transform, after Randal L. Schwartz, who popularised the technique in Perl.

提交回复
热议问题