wheres pythonmonks wrote:
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
In [31]: import re
In [32]: sum(int(x) for x in re.findall("..", s))
Out[32]: 102
To get a tuple instead of the sum, just do:
In [33]: tuple(int(x) for x in re.findall("..", s))
Out[33]: (12, 34, 56)
--
http://mail.python.org/mailman/listinfo/python-list