Sorting a multidimensional array by multiple keys

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • bearophileHUGS@lycos.com

    #16
    Re: Sorting a multidimensiona l array by multiple keys

    Steven Bethard:
    there's almost never a reason to use the cmp= argument to
    sort() anymore. It's almost always better to use the key= argument.
    I always use key now, but maybe cmp uses less memory. There can be few
    situations where cmp is better still.

    Bye,
    bearophile

    Comment

    • Alex Martelli

      #17
      Re: Sorting a multidimensiona l array by multiple keys

      Steven Bethard <steven.bethard @gmail.comwrote :
      Thomas Krüger wrote:
      Alex Martelli schrieb:
      Thomas Krüger <newsgroups@nos pam.nowire.orgw rote:
      >def sorter(a, b):
      > return cmp(a.id, b.id)
      >>
      >obj_lst.sort(s orter)
      A MUCH better way to obtain exactly the same semantics would be:
      >
      def getid(a):
      return a.id
      >
      obj_list.sort(k ey=getid)
      Frankly speaking the purpose of the example was to show how to pass a
      function as argument for the sort method.
      Your code may be more efficient but it explains something different.
      >
      Yes, but there's almost never a reason to use the cmp= argument to
      sort() anymore. It's almost always better to use the key= argument.
      Exactly. Passing a "comparison function" rather than a key-extraction
      function is rarely a good idea -- except for some extremely complicated
      cases involving e.g. certain string (or more complicated) fields needing
      to be sorted in the reverse direction from others. In practice, the
      existence of that argument and its prominent position as the first
      positional argument is due entirely to backwards compatibility issues.


      Alex

      Comment

      Working...