开发者

Convert list of Fractions to floats in Python

开发者 https://www.devze.com 2023-01-13 12:51 出处:网络
I have a list of fractions, such as: data = [开发者_如何学C\'24/221 \', \'25/221 \', \'24/221 \', \'25/221 \', \'25/221 \', \'30/221 \', \'31/221 \', \'31/221 \', \'31/221 \', \'31/221 \', \'30/221 \

I have a list of fractions, such as:

data = [开发者_如何学C'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.


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]


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


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]


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


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


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]

0

精彩评论

暂无评论...
验证码 换一张
取 消