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

B

boblatest

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.

robert
 
A

alex23

['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)
 
C

Chris Rebert

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
 
U

Ulrich Eckhardt

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.

temp = map(float, x)
ftuple = tuple(temp)

Of course this is also possible to write in a single line.

Uli
 
M

Mike Kazantsev

this is the conversion I'm looking for:

['1.1', '2.2', '3.3'] -> (1.1, 2.2, 3.3)

Since itertools are useful in nearly every module and probably are
imported already...

import itertools as it
ftuple = tuple(it.imap( float, line.split('; ') ))

--
Mike Kazantsev // fraggod.net

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.11 (GNU/Linux)

iEYEARECAAYFAkoRYrYACgkQASbOZpzyXnEGpwCeOD8hfudjvIpRAuV59Kd52lI+
5ZcAnRbdyXWYFgwZUiriFWJ354Q6gP9v
=N4w1
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top