sort the list

Duncan Booth duncan.booth at invalid.invalid
Mon Nov 21 09:41:12 EST 2005


Daniel Schüle wrote:

> I can offer you some more brain food to digest ;)
> maybe you can adapt this solution, but that depends
> on your problem
> I find it clear and I used it recently
> 
> >>> name, age, salary = "name", "age", "salary"
> >>> people = [
> ... {name:"oliver", age:25, salary:1800},
> ... {name:"mischa", age:23, salary:0},
> ... {name:"peter", age:22, salary:1500},
> ... ]
> >>>
> >>> def cmpFabrik(field):
> ...     def cmpFunc(x,y):
> ...             return cmp(x[field], y[field])
> ...     return cmpFunc
> >>> people.sort(cmp = cmpFabrik(name))
> >>> people.sort(cmp = cmpFabrik(age))
> >>> people.sort(cmp = cmpFabrik(salary))
> 
> it's not very OO but sometimes things are simple
> and no need to create a class

I thought you said you were using Python 2.4, so why didn't you just do 
this?:

>>> from operator import itemgetter
>>> people.sort(key=itemgetter('name'))
>>> people.sort(key=itemgetter('age'))
>>> people.sort(key=itemgetter('salary'))

and if you want to sort on multiple keys, this could be useful:

>>> def multikey(*args):
	def makekey(v):
		return tuple(a(v) for a in args)
	return makekey

>>> people.sort(key=multikey(itemgetter('age'), itemgetter('name')))



More information about the Python-list mailing list