How to convert a list of strings to a tuple of floats?

Chris Rebert clp2 at rebertia.com
Mon May 18 04:00:10 EDT 2009


On Mon, May 18, 2009 at 12:51 AM, boblatest at googlemail.com
<boblatest at googlemail.com> wrote:
> Hello group,
>
> this is the conversion I'm looking for:
>
> ['1.1', '2.2', '3.3'] -> (1.1, 2.2, 3.3)
>
> Currently I'm "disassembling" the list by hand, like this:
>
>    fields = line.split('; ')
>    for x in range(len(fields)):
>        fields[x] = float(fields[x])
>    ftuple = tuple(fields)
>
> Of course it works, but it looks inelegant. Is there a more Pythonisch
> way of doing this? In C I'd just use sscanf.

ftuple = tuple(float(field) for field in fields)

See the docs on "generator expressions" for more info.

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list