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

alex23 wuwei23 at gmail.com
Mon May 18 03:58:59 EDT 2009


On May 18, 5:51 pm, "boblat... at googlemail.com"
<boblat... at googlemail.com> wrote:
> ['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.

Either:

    ftuple = tuple(map(float, fields))

Or the BDFL-endorsed:

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



More information about the Python-list mailing list