Packing data

bvdpoel at uniserve.com bvdpoel at uniserve.com
Wed May 1 22:27:38 EDT 2002


Jeff Shannon wrote:
> 
> In article <3CD0850E.94E6EC5F at uniserve.com>, bvdpoel at uniserve.com
> says...
> >
> > I'm doing some midi stuff and need to pack ints into a byte string. I'm
> > doing
> >
> > def mkstring(var):
> >  ret = ""
> >  for a in var:
> >   ret += chr(a)
> >  return ret
> 
> Presuming that var is a list of ints, the following will be much
> more efficient than your code, without requiring array/struct.
> 
> def mkstring(var):
>     var = [chr(a) for a in var]
>     return ''.join(var)
> 
> The first line goes through your list of ints and converts it
> into a list of single characters.  The second line then joins
> that list into a single string, and returns it.  The biggest
> problem with your version is that, by using repeated string
> concatenation, you're creating a new, progressively longer and
> longer, temporary string item for each element of your list, in
> addition to the single-character string.  For lists of any
> significant length, this quickly becomes *very* inefficient.


Ahh, list comprehensions! I knew that I should have looked/learned that.
Thanks. I'll give it a go...should work just dandy!

-- 
Bob van der Poel ** Wynndel, British Columbia, CANADA **
EMAIL: bvdpoel at uniserve.com
WWW:   http://users.uniserve.com/~bvdpoel





More information about the Python-list mailing list