Unanswered Questions in python.faqts.com
Will Ware
wware at world.std.com
Mon Aug 21 22:56:53 EDT 2000
Fiona Czuczman (fiona at sitegnome.com) wrote:
> FAQTS : Computers : Programming : Languages : Python : Language and
> Syntax
> How should a sortable sequence be implemented?
> http://www.faqts.com/knowledge-base/view.phtml/aid/5367/fid/241/lang/
Objects can be sorted as long as they can be compared. Fundamental
types (ints, floats, strings) can be compared with the globally defined
cmp() function. cmp(x,y) returns a negative integer if x<y, zero if x==y,
and a positive integer if x>y. If the 'sort' method is called on a list
of objects, the list will be sorted in increasing order:
x = [3,1,4,1,5,9,2,6]
x.sort()
print x --> [1,1,2,3,4,5,6,9]
Classes can be made sortable by defining a __cmp__ method for them. For
example, to sort a list of 3-d points in decreasing order of z, you could
write:
class Point:
def __init__(self, x,y,z):
self.x, self.y, self.z = x, y, z
def __cmp__(self, other):
return -cmp(self.z, other.z)
# or: return cmp(other.z, self.z)
Now if you create a list of points (x) and call x.sort(), the points will
be sorted in decreasing-z order.
Another way to define the sorting criterion is to pass a cmp-like function
as the argument to x.sort(). To re-sort your points in increasing-y order,
you can write:
x.sort(lambda self,other: cmp(self.y, other.y))
or if you don't like lambdas:
def y_sorter(u,v):
return cmp(u.y, v.y)
x.sort(y_sorter)
--
# - - - - - - - - - - - - - - - - - - - - - - - -
# Resistance is futile. Capacitance is efficacious.
# Will Ware email: wware @ world.std.com
More information about the Python-list
mailing list