Nice way to cast a homogeneous tuple

wheres pythonmonks wherespythonmonks at gmail.com
Wed Jul 28 09:15:24 EDT 2010


A new python convert is now looking for a replacement for another perl idiom.

In particular, since Perl is weakly typed, I used to be able to use
unpack to unpack sequences from a string, that I could then use
immediately as integers.

In python, I find that when I use struct.unpack I tend to get strings.
 (Maybe I am using it wrong?)

def f(x,y,z): print x+y+z;

f( *struct.unpack('2s2s2s','123456'))
123456

(the plus concatenates the strings returned by unpack)

But what I want is:

f( *map(lambda x: int(x), struct.unpack('2s2s2s','123456')))
102

But this seems too complicated.

I see two resolutions:

1.  There is a way using unpack to get out string-formatted ints?

2.  There is something like map(lambda x: int(x).... without all the
lambda function call overhead.  (e.g., cast tuple)?
  [And yes: I know I can write my own "cast_tuple" function -- that's
not my point.  My point is that I want a super-native python inline
solution like (hopefully shorter than) my "map" version above.  I
don't like defining trivial functions.]

W



More information about the Python-list mailing list