Python beginner - Sorting tuples using lambda functions

后端 未结 3 1592
生来不讨喜
生来不讨喜 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条回答
  •  隐瞒了意图╮
    2021-01-15 03:22

    Sometimes when starting to work with lambda, it's easier to write out the function explicitly. Your lambda function is equivalent to:

    def sort_key(pair):
        return pair[1]
    

    If we want to be more verbose, we can unpack pair to make it even more obvious:

    def sort_key(pair):
        int_value, string_value = pair
        return string_value
    

    Because list.sort orders the items based on the return value of the key function (if present), now we see that it is sorting the tuples by their string value. Since strings sort lexicographically, "four" comes before "one" (think alphabetical order).

提交回复
热议问题