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.
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 .
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.
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.
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]
import fractions
data = [str(round(float(fractions.Fraction(x)), 2)) for x in data]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With