2010-08-26 67 views
7

彩車我有分數的列表,如:轉換列表在Python

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

我怎麼會去將這些成浮點數,例如

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

Fraction模塊似乎只能轉換爲Fractions(不)和float([x])需要一個字符串或整數。

+0

你想TRUNC在第二個小數點後吃飯或回合? – 2010-08-26 19:17:02

回答

11
import fractions 
data = [float(fractions.Fraction(x)) for x in data] 

或完全匹配的示例(數據用串結束):

import fractions 
data = [str(float(fractions.Fraction(x))) for x in data] 
0
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]

1
import fractions 
data = [str(round(float(fractions.Fraction(x)), 2)) for x in data] 
0
data = [ x.split('/') for x in data ] 
data = [ float(x[0])/float(x[1]) for x in data ] 
0

嵌套列表解析將讓你的答案無需導入額外的模塊(分數是隻在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'] 
+1

分數在2.6。 – carl 2010-08-26 20:30:17

+0

糟糕!你是對的。我的錯。 – 2010-08-27 03:20:41

1

使用分數模塊是好的,整齊,但也相當重量級(慢)相比於簡單的字符串分割或分區

這個列表解析創建花車爲得票最多的答案確實

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

如果你希望兩個小數位串

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