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

Ben Finney ben+python at benfinney.id.au
Mon May 18 04:44:35 EDT 2009


"boblatest at googlemail.com" <boblatest at googlemail.com> writes:

> 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?

You can create a tuple by calling the tuple type with an iterable, where
each item from the iterable becomes an element in the created tuple.

    >>> tuple([4, 5, 6])
    (4, 5, 6)

You can create an iterable with a generator expression:

    >>> for n in (x**2 for x in range(5)):
    ...     print n
    ... 
    0
    1
    4
    9
    16

Combine the two, creating a tuple from a generator expression:

    >>> fields = ['1.1', '2.2', '3.3']
    >>> record = tuple(
    ...     float(text) for text in fields)
    >>> record
    (1.1000000000000001, 2.2000000000000002, 3.2999999999999998)

-- 
 \        “Nothing so needs reforming as other people's habits.” —Mark |
  `\                                       Twain, _Pudd'n'head Wilson_ |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list