How can I get rid of lambda

Steve Williams sandj.williams at gte.net
Sun Oct 15 20:11:29 EDT 2000


I'm working with IBM packed decimal data.  The following code works OK,
but there are millions of rows and 10 to 50 columns per row.  I want as
much speed as I can get.

How can I avoid the lambda in the following unpack function?  Or better,
is there a faster way?

By the way, if you want a testimonial to Python's capabilities, do a
Google search on 'packed decimal' and have a look at some of the Java
solutions to this problem.

===============================================

"""Unpack an IBM packed decimal string"""
import string

#Get rid of the dots
fnJoin = string.join
fnTranslate = string.translate

#Create translate tables for the left and right nybbles
_strSource = ""
for _i in range(256): _strSource = _strSource + chr(_i)
_trtLeftNybble = string.maketrans(_strSource, \
    "0"*16  + "1"*16 + "2"*16 + "3"*16 + "4"*16 + \
    "5"*16 + "6"*16 + "7"*16 + "8"*16 + "9"*16 + "."*96)
_trtRightNybble = string.maketrans(_strSource,"0123456789+-+-++"*16)
del _strSource
del _i

def unpack(strPacked):
    return fnJoin(map(lambda chrLeft, chrRight: chrLeft + chrRight,\
        fnTranslate(strPacked,_trtLeftNybble),\
        fnTranslate(strPacked,_trtRightNybble)),"")

try:
    packedNumber = '\x01\x23\x45\x67\x89\x0f'
    print unpack(packedNumber)
except RuntimeError, e:
    print e

try:
    packedNumber = '\x01\x23\x45\x67\x89\x0d'
    print unpack(packedNumber)
except RuntimeError, e:
    print e






More information about the Python-list mailing list