python - sorting a sequence with key function [dup

2019-06-01 09:18发布

问题:

This question already has an answer here:

  • How does the key argument in python's sorted function work? 3 answers

It is unclear to me how the following works:

In [1]: student_tuples = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
In [2]: sorted(student_tuples, key=lambda student: student[2])
Out [2]: [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] # sort by age

but,

In [3]: st = lambda student: student[2]
In [4]: st(student_tuples)
Out [4]: ('dave', 'B', 10)

Why does the [2] in the former sample refer to the index for the individual tuples, when in a lambda function it returns the 2nd tuple in the list?

回答1:

Because when you're sorting, the key function is called once for every element of the list being sorted. That's why it's lambda student: not lambda student_tuples: (not that the naming of parameters changes anything, just explaining the naming choice).

You can see this directly by printing the argument of the key function:

student_tuples = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

def my_key(student):
    print(student)
    return student[2]

sorted(student_tuples, key=my_key)
# calls to my_key print:
# ('john', 'A', 15)
# ('jane', 'B', 12)
# ('dave', 'B', 10)

my_key(student_tuples)
# prints (not returns):
# [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]