best way to determine sequence ordering?

Edward Elliott nobody at 127.0.0.1
Fri Apr 28 16:06:04 EDT 2006


gry at ll.mit.edu wrote:
> class Item(object):
>    def __init__(self, value):
>       self.val=value
>       self.order = dict(c=0, a=1, d=2, b=3)
>    def __cmp__(self, other):
>       return cmp(self.order[self.val], self.order[other.val])

An object that keeps track of the order it's stored in an external container
seems bass-ackwards to me (if you'll pardon the expression).  How do you
update the order?  Why does every object need to carry around a global
ordering?  What happens if you need two separate orderings like a,b,c,d and
a,c,d,b?  And it isn't clear at all what the < operator is comparing in
your example:

a=Item('A')
b=Item('B')
if a < b: something

I'd put the ordering logic in the container instead.  Something like this:

class mylist(list):
    def before (me, a, b):
        return me.index(a) < me.index(b)

l = mylist (['C', 'A', 'D', 'B'])
if l.before('A', 'D'):
    something

This seems clearer and more flexible.  You'll still have to handle
exceptions when a or b aren't in the list.





More information about the Python-list mailing list