user431392
user431392

Reputation: 91

Convert list of Fractions to floats in Python

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.

Upvotes: 9

Views: 5939

Answers (7)

redwood_gm
redwood_gm

Reputation: 353

All of the previous answers seem to me to be overly complicated. The simplest way to do this, as well as doing numerous other conversions, is to use eval().

The following is one method

l=['1/2', '3/5', '7/8']
m=[]
for i in l
   j=eval(i)
   m.append(j)

The list comprehension version of the above is another method

m= [eval(i) for i in l] 

each method results in m as

[0.5, 0.75, 0.875]

Upvotes: 0

Yves Dorfsman
Yves Dorfsman

Reputation: 3055

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

Upvotes: 0

Kirk Strauser
Kirk Strauser

Reputation: 30947

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']

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304175

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)]

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

import fractions
data = [str(round(float(fractions.Fraction(x)), 2)) for x in data]

Upvotes: 2

Unel
Unel

Reputation: 1

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]

Upvotes: 0

carl
carl

Reputation: 50554

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]

Upvotes: 15

Related Questions