best way to determine sequence ordering?

gry at ll.mit.edu gry at ll.mit.edu
Fri Apr 28 13:45:56 EDT 2006


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




More information about the Python-list mailing list