[Tutor] Sort a list following the order of other list

Kent Johnson kent37 at tds.net
Tue Aug 23 04:07:36 CEST 2005


Jonas Melian wrote:
> best = [ [1024, 768], [800, 600], [640, 480] ]  (it's larger)
> 
> modes = [
> (24, [1280, 1024]),
> (24, [1024, 768]),
> (24, [640, 480]),
> (16, [1600, 1200]),
> (16, [1280, 1024]),
> (15, [320, 200]),
> ]
> 
> I want to create a list with ALL elements of 'modes', but following the 
> order of list 'best' (if exist the number). At the end the rest of 
> numbers in modes, are added too. And all this for each modes[0] (24, 16, 
> 15, ...)

In Python 2.4 you can get clever with the key function to sort() or sorted():

def keyFunc(mode):
  depth, dims = mode
  try:
      ix = best.index(dims)
  except ValueError:
      ix = len(modes)
  
  return (ix, -depth, -dims[0])

for mode in sorted(modes, key=keyFunc):
  print mode

For Python 2.3 you can to use the decorate-sort-undecorate idiom. To do this you build an intermediate list with the that will sort the way you want, sort it, an remove the extra stuff you added at the beginning. The same keyFunc will work:

deco = [(keyFunc(mode), mode) for mode in modes]
deco.sort()
modes = [mode for (key, mode) in deco]
for mode in modes:
    print mode




More information about the Tutor mailing list