# Sorting a multidimensional array by multiple keys

Paulo da Silva psdasilvaX at esotericaX.ptX
Mon Apr 2 04:03:23 CEST 2007

```Rehceb Rotkiv escreveu:
> Hello everyone,
>
> can I sort a multidimensional array in Python by multiple sort keys? A
> litte code sample would be nice!

class MyList(list):
# This is the index of the element to be compared
CmpIndex=0

# Comparision methods
@staticmethod
def __cmp_pars(x,y):
if isinstance(x,MyList):
x=x[MyList.CmpIndex]
if isinstance(y,MyList):
y=y[MyList.CmpIndex]
return x,y
def __cmp__(self,other):
s,o=MyList.__cmp_pars(self,other)
return cmp(s,o)
def __lt__(self,other):
s,o=MyList.__cmp_pars(self,other)
return s<o
def __le__(self,other):
s,o=MyList.__cmp_pars(self,other)
return s<=o
def __gt__(self,other):
s,o=MyList.__cmp_pars(self,other)
return s>o
def __ge__(self,other):
s,o=MyList.__cmp_pars(self,other)
return s>=o
def __eq__(self,other):
s,o=MyList.__cmp_pars(self,other)
return s==o
def __ne__(self,other):
s,o=MyList.__cmp_pars(self,other)
return s!=o

Use:

x=MyList(<list of lists>)
MyList.CmpIndex=2 # Compare by index 2
x.sort()

May be there is a better solution ...
HTH
Paulo

```