[Zope] sort in python script dynamically?

Alec Mitchell apm13 at columbia.edu
Tue Jan 13 03:47:37 EST 2004


On Tuesday 13 January 2004 12:19 am, Andre Meyer wrote:
> def sort_by_field(self, list, f):
>       list.sort(lambda a, b: cmp(a.f, b.f))
>
> x = myObject(i, j, k)
> y = myObject(l, m, n)
> list = [x, y]
> sort_by_field(list)
>
> How can an attribute name (a string) be translated in the actual attribute?

getattr(a, f)

Though using the 'decorate-sort-undecorate' idiom will likely perform much 
better, especially if you are sorting a large number of objects.  An example 
is available here:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234

in this case it would be:

def sort_by_field(list, f):
	decorated = [(getattr(obj, f), obj) for obj in list]
	decorated.sort()
	return [a[1] for a in decorated]

If you prefer to sort in place that's just a trivial change (list[:] = ${the 
return statement}), as is adding secondary characteristics to sort on, or  
insuring sort stability (as in the link above).  Also, it's not clear why you 
are making your sort function a member of a particular class (judging by the 
'self' parameter), it probably makes more sense as a general utility 
function.

Alec Mitchell




More information about the Zope mailing list