Multidimensional sort

James Stroud jstroud at mbi.ucla.edu
Wed Oct 10 16:53:42 EDT 2007


termiflyer wrote:
> How do I sort this:
> 
>>>> a
> [['3', ['1', '0']], ['4', ['3', '0'], ['2', '0']]]
> 
> where the list can be arbitrarily large by the 3rd dimension (i
> think).  E.g.:
> 
>>>> a
> [['3', ['1', '0']], ['4', ['2', '0'], ['3', '0']]]
> 
> 
> Thanks
> 

Your difficulties come from an ill-defined third dimension. You should 
reorganize to produce this heretofore potential third dimension:

    a = [(i[0], i[1:]) for i in a]

Then sort the reorganized list now that it has a structure amenable to 
sorting:

    for i in a:
      i[1].sort()

Then, if you are pressed, transform it back:

    a = [[i[0]] + i[1] for i in a]

E.g.:

   py> a = [['3', ['1', '0']], ['4', ['3', '0'], ['2', '0']]]
   py> a = [(i[0], i[1:]) for i in a]
   py> a
   [('3', [['1', '0']]), ('4', [['3', '0'], ['2', '0']])]
   py>    for i in a:
   ...      i[1].sort()
   ...
   py> a
   [('3', [['1', '0']]), ('4', [['2', '0'], ['3', '0']])]
   py> a = [[i[0]] + i[1] for i in a]
   py> a
   [['3', ['1', '0']], ['4', ['2', '0'], ['3', '0']]]

James



-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA  90095

http://www.jamesstroud.com



More information about the Python-list mailing list