How to use a 5 or 6 bit integer in Python?

Oren Tirosh oren-py-l at hishome.net
Sat Dec 20 08:12:11 EST 2003


On Fri, Dec 19, 2003 at 06:27:59AM +0000, Rainer Deyke wrote:
> Encoding the key tuples as strings is easy (''.join([chr(x) for x in
> the_tuple]).  Encoding the ints in the data tuples is just as easy.  I'm not
> sure if those are enough to solve your problem.

Using strings is a really, really good idea. Strings are compact and
Python dictionaries are highly optimized for use with string keys with
tricks like caching of the string hash and faster code paths for special 
cases like dicts that have only string keys.

There is a much faster way for converting tuples of integers to strings. 
Instead of using the Python tuple type use arrays of bytes and then apply 
the array object's .tostring() method:

>>> from array import array
>>> the_array = array('b', range(40))
>>> the_string = the_array.tostring()

It's about 35 times faster than ''.join([chr(x) for x in the_array])

>>> back_to_array = array('b', the_string)

   Oren





More information about the Python-list mailing list