<code class= "Hljs python has-numbering" ><span class= "hljs-comment" >#-*-, Coding:utf-8-*-</span> <span class= "Hljs-comment" ># when sorting, you can map an object to keys</span> <span class= "Hljs-comment" with a lambda expression ># You can also use the Attrgetter and Itemgetter functions in the operator package to improve efficiency </span> <span class= "hljs-comment" ># reference http:// wiki.python.org/moin/howto/sorting</span> <span class= "hljs-comment" ># consider Student objects </span> < Span class= "Hljs-class" ><span class= "Hljs-keyword" >class</span> <span class= "Hljs-title" > student</span>:</span> <span class= "hljs-function" ><span class= "Hljs-keyword" >def</ span> <span class= "Hljs-title" >__init__</span><span class= "Hljs-params" > (self, name, grade, age ) </span>:</span> Self.name = name Self.grade = Grade Self.age = Age &L T;span class= "hljs-function" ><span class= "Hljs-keyword" >def</span> <spanclass= "Hljs-title" >__repr__</span><span class= "Hljs-params" > (self) </span>:</span> & Lt;span class= "Hljs-keyword" >return</span> repr (Self.name, Self.grade, self.age)) <span class= " Hljs-comment "># set up a group of Student objects </span> students = [Student (<span class=" hljs-string "> ' Jane ' </span& gt;, <span class= "hljs-string" > ' B ' </span>, <span class= "Hljs-number" >12</span>), Student ( <span class= "hljs-string" > ' John ' </span> <span class= "hljs-string" > ' A ' </span> <span class= "Hljs-number" >12</span>), Student (<span class= "hljs-string" > ' Dave ' </span> <span class= "hljs-string" > ' B ' </span>, <span class= "Hljs-number" >10</span>),] <span class= " Hljs-keyword ">from</span> operator <span class=" Hljs-keyword ">import</span> Itemgetter, Attrgetter <span class= "Hljs-comment" ># to students according to age </span> <span CLass= "Hljs-keyword" >print</span> sorted (students, Key=attrgetter (<span class= "hljs-string" > ' Age ') </span>) <span class= "Hljs-comment" ># its equivalent to </span> <span class= "Hljs-keyword" >print</ Span> sorted (students, Key=<span class= "Hljs-keyword" >lambda</span> o:o.age) <span class= " Hljs-comment "># output: >>> [(' Dave ', ' B ',], (' Jane ', ' B ',"), (' John ', ' A ', ')]</span> <span class = "Hljs-comment" ># can also be sorted by more than one key, sorted by age and then grade </span> <span class= "Hljs-keyword" >print</span> Sorted (students, Key=attrgetter (<span class= "hljs-string" > ' Age ' </span>, <span class= "hljs-string" > ' Grade ' </span>) <span class= ' hljs-comment ' ># output: >>> [(' Dave ', ' B ',], (' John ', ' A ', ', '), (' J Ane ', ' B ',]</span></code>