views:

162

answers:

6

I have a list of fractions, such as:

data = ['24/221 ', '25/221 ', '24/221 ', '25/221 ', '25/221 ', '30/221 ', '31/221 ', '31/221 ', '31/221 ', '31/221 ', '30/221 ', '30/221 ', '33/221 ']

How would I go about converting these to floats, e.g.

data = ['0.10 ', '0.11 ', '0.10 ', '0.11 ', '0.13 ', '0.14 ', '0.14 ', '0.14 ', '0.14 ', '0.14 ', '0.13 ', '0.13 ', '0.15 ']

The Fraction module seems to only convert to Fractions (not from) and float([x]) requires a string or integer.

Thanks in advance.

+7  A: 
import fractions
data = [float(fractions.Fraction(x)) for x in data]

or to match your example exactly (data ends up with strings):

import fractions
data = [str(float(fractions.Fraction(x))) for x in data]
carl
A: 
def split_divide(elem):
    (a,b) = [float(i) for i in elem.split('/')]
    return a/b

map(split_divide, ['1/2','2/3'])

[0.5, 0.66666666666666663]

unel
+1  A: 
import fractions
data = [str(round(float(fractions.Fraction(x)), 2)) for x in data]
Tim Pietzcker
A: 

data = [ x.split('/') for x in data ] data = [ float(x[0]) / float(x[1]) for x in data ]

A: 

Nested list comprehensions will get you your answer without importing extra modules (fractions is only in Python 2.6+).

>>> ['%.2f' % (float(numerator)/float(denomator)) for numerator, denomator in [element.split('/') for element in data]]
['0.11', '0.11', '0.11', '0.11', '0.11', '0.14', '0.14', '0.14', '0.14', '0.14', '0.14', '0.14', '0.15']
Just Some Guy
Fractions is in 2.6.
carl
Oops! You're right. My bad.
Just Some Guy
+1  A: 

Using the fraction module is nice and tidy, but is quite heavyweight (slower) compared to simple string split or partition

This list comprehension creates the floats as the answer with the most votes does

[(n/d) for n,d in (map(float, i.split("/")) for i in data)]

If you want the two decimal place strings

["%.2f"%(n/d) for n,d in (map(float, i.split("/")) for i in data)]
gnibbler