Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 896
user431392 Avatar asked Aug 26 '10 19:08

user431392


People also ask

How do you convert a Fraction to a float in Python?

Convert a fraction to a floating-point number: float() You can convert Fraction to a floating-point number with float() . The result of an operation between Fraction and float is automatically converted to float .

How do you convert a list to a float in Python?

The most Pythonic way to convert a list of strings to a list of floats is to use the list comprehension floats = [float(x) for x in strings] . It iterates over all elements in the list and converts each list element x to a float value using the float(x) built-in function.

How do you convert fractions in Python?

To convert a ratio of two integers to fraction, we use Fraction() method of fractions module and pass the numerator as the first argument and the denominator as the second argument. The function returns a fraction object as follows.


2 Answers

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]
like image 100
carl Avatar answered Oct 01 '22 14:10

carl


import fractions
data = [str(round(float(fractions.Fraction(x)), 2)) for x in data]
like image 43
Tim Pietzcker Avatar answered Oct 01 '22 14:10

Tim Pietzcker