Nice way to cast a homogeneous tuple

Tim Chase python.list at tim.thechases.com
Wed Jul 28 10:14:06 EDT 2010


On 07/28/10 08:15, wheres pythonmonks wrote:
> f( *map(lambda x: int(x), struct.unpack('2s2s2s','123456')))
> 102
>
> 1.  There is a way using unpack to get out string-formatted ints?

well, you can use

 >>> s = '123456'
 >>> [int(s[i:i+2]) for i in range(0, len(s), 2)]
[12, 34, 56]
 >>> f(*_)
102

While your "f()" is just a boring placeholder I assume, you could 
also write that as

  sum(int(s[i:i+2]) for i in range(0, len(s), 2))

and skip creating f() altogether if all it does is add its arguments.

-tkc






More information about the Python-list mailing list