代碼1:排序工作的關鍵參數如何?
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
代碼2:
>>> student_tuples = [
... ('john', 'A', 15),
... ('jane', 'B', 12),
... ('dave', 'B', 10),
... ]
>>> from operator import itemgetter, attrgetter
>>>
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
爲什麼在代碼1中,()
省略key=str.lower
,並且如果被包括括號它報告錯誤,但在代碼2 key=itemgetter(2)
,所述括號保留?
謝謝你對水晶般清晰的解釋,比雷埃夫斯! –