python sorting 2dim. array ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • fredo66@fulladsl.be

    python sorting 2dim. array ?

    hello,
    Can someone help me with this:
    I have a array like this

    list[rowindex][colomindex]

    where rows are the records and colom the fields. If I use the .sort()
    method on 'list' the data is sorted on the items of the first colom.
    But I want to sort on the second colom as first (and as second
    sortfield the first colom).

    What is the shortest code for this pls ?

    (all fields are text value, first colom is name, second category)
  • fredo66@fulladsl.be

    #2
    Re: python sorting 2dim. array ?

    remark: The server is using python server version 2.3.4

    Comment

    • Peter Otten

      #3
      Re: python sorting 2dim. array ?

      fredo66@fullads l.be wrote:
      hello,
      Can someone help me with this:
      I have a array like this
      >
      list[rowindex][colomindex]
      >
      where rows are the records and colom the fields. If I use the .sort()
      method on 'list' the data is sorted on the items of the first colom.
      But I want to sort on the second colom as first (and as second
      sortfield the first colom).
      >
      What is the shortest code for this pls ?
      >
      (all fields are text value, first colom is name, second category)
      >>items = [(1,2), (2,2), (2,1)]
      >>items.sort(la mbda x, y: cmp(x[1::-1], y[1::-1]))
      >>items
      [(2, 1), (1, 2), (2, 2)]

      If you want something more efficient, see

      Contents: Programming FAQ- General questions- Is there a source code-level debugger with breakpoints and single-stepping?, Are there tools to help find bugs or perform static analysis?, How can I c...


      Peter

      Comment

      • bearophileHUGS@lycos.com

        #4
        Re: python sorting 2dim. array ?

        fred...@fullads l.be:
        list[rowindex][colomindex]
        I want to sort on the second colom as first (and as
        second sortfield the first colom).
        A good way, in Python 2.5:
        >>from operator import itemgetter
        >>a = [[1, 2], [3, 1], [2, 5], [7, 1]]
        >>a.sort(key=it emgetter(1, 0))
        >>a
        [[3, 1], [7, 1], [1, 2], [2, 5]]

        Bye,
        bearophile

        Comment

        Working...