tuples, index method, Python's design
Carsten Haese
carsten at uniqsys.com
Tue Apr 10 10:03:06 EDT 2007
On Tue, 2007-04-10 at 13:21 +0000, Antoon Pardon wrote:
> > But if you are so eager to rewrite, how about the following:
> >
> > I am using the struct module to get binary data from a file.
> > Sometimes I want to skip until I find a particular binary
> > number. Somewhat simplified it looks like this:
> >
> >
> > class Itemfile:
> > def __init__(self, fn):
> > self.fl = open(fn)
> > self.ix = 80
> >
> > def nextitem(self):
> > if self.ix == 80:
> > self.buf = struct.unpack("80i", self.fl.read(320))
> > self.ix = 0
> > result = self.buf[self.ix]
> > self.ix += 1
> > return result
> >
> > def skipuntil(self, val):
> > done = False
> > while not done:
> > try:
> > self.ix = self.buf.index(val, self.ix)
> > done = True
> > except ValueError:
> > self.ix = 0
> > self.buf = struct.unpack("80i", self.fl.read(320))
> >
> >
> > Now I'm sure you can rewrite this without the need of tuple.index.
> > It just seems odd that I have to go through extra hoops here to
> > get the effect of tuple.index because struct.unpack returns its result
> > in a tuple and a tuple doesn't provide index.
Your data is an array. Choosing a data structure that doesn't fit your
data is always going to cause pain. Instead of using struct.unpack, you
should use array.array, and voila!, you get an index method.
-Carsten
More information about the Python-list
mailing list