How do you pass a standard operator such as '<' as a parameter?
Lonnie Princehouse
fnord at u.washington.edu
Thu Nov 20 23:42:27 EST 2003
> For non-standard data types, you would obviously define a '<' function and
> then pass it as a parameter at initialisation, but how can you pass one of
> the standard operators? i.e. '<'.
Lambda!
my_list = OrderedList([], comparator = lambda a,b: a < b)
You might also consider using the same style of comparator function
that list.sort() uses. This returns 1 for greater than, 0 for equal,
and -1 for less than. Then you could use the builtin cmp function,
and could also sort the OrderedList directly with the comparator:
class OrderedList(list):
def __init__(self, initial=[], comparator=None):
list.__init__(self, initial)
self.ComparisonFunc = comparator
self.sort()
def sort(self, *args):
# use self.ComparisonFunc as default
if len(args):
comparator = args[0]
elif self.ComparisonFunc:
args.append(self.ComparisonFunc)
list.sort(self, *args)
More information about the Python-list
mailing list