best way to determine sequence ordering?

John Salerno johnjsal at NOSPAMgmail.com
Fri Apr 28 14:05:37 EDT 2006


gry at ll.mit.edu wrote:
> index is about the best you can do with the structure you're using.
> If you made the "items" instances of a class, then you could define a
> __cmp__ member, which would let you do:
> 
> a=Item('A')
> b=Item('B')
> if a<b: something
> 
> The Item class could use any of various means to maintain order
> information. If there are not too many values, it could have a
> dictionary storing an integer for the order:
> 
> 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])
> 
> If you don't care about performance, or you find it clearer, just use:
>       self.order = ['C', 'A', 'D', 'B']
> and
>    def __cmp__(self, other):
>       return cmp(self.order.index(self.value),
> self.order.index(other.value))
> 
> 
> -- George Young
> 

Thanks. As I progressed with my little project, I was beginning to 
wonder about making a class, so your suggestions might be helpful if I 
convert it to that.



More information about the Python-list mailing list