2015-10-21 17 views
2

我有一個字符串的混合,並在列表中漂浮:如果可能,將字符串列表轉換爲浮點。 - 蟒蛇

line = [u'6.0', u'5.0', u'1.2', u'S\xf3lo', u'_START_', u'utilizamos', u'only', u'We', u'use', u'0', u'0', u'1', u'0', u'0', u'0', u'0.2', u'0.1', u'0.2', u'0', u'0', u'0', u'ADV', u'RB', u'9', u'0', u'OK'] 

我要轉換的「鑄能」項目列表中的浮動,即輸出:

[6.0, 5.0, 1.2, u'S\xf3lo', u'_START_', u'utilizamos', u'only', u'We', u'use', 0, 0, 1, 0, 0, 0, 0.2, 0.1, 0.2, 0, 0, 0, u'ADV', u'RB', 9, 0, u'OK'] 

我試過這個,但有沒有一個不太詳細的方式來做到這一點?

def super_munger(_lst): 
    lst = [] 
    for item in _lst: 
    try: 
     item = float(item) 
    except: 
     item = item 
    lst.append(item) 
    return item 
+1

你說的「清單詳細」 –

+0

的意思笑,錯字更簡潔=) – alvas

回答

3

您可以使用這樣的事情 - 在一個函數如果你想它

def float_cast(item): 
    try: 
     return float(item) 
    except ValueError: 
     return item 

result_lst = [float_cast(item) for item in lst] #`lst` is your original list 

,你可以做 -

def super_munger(_lst): 
    return [float_cast(item) for item in _lst] 

演示 -

>>> def float_cast(item): 
...  try: 
...   return float(item) 
...  except ValueError: 
...   return item 
... 
>>> line = [u'6.0', u'5.0', u'1.2', u'S\xf3lo', u'_START_', u'utilizamos', u'only', u'We', u'use', u'0', u'0', u'1', u'0', u'0', u'0', u'0.2', u'0.1', u'0.2', u'0', u'0', u'0', u'ADV', u'RB', u'9', u'0', u'OK'] 
>>> result = [float_cast(item) for item in line] 
>>> result 
[6.0, 5.0, 1.2, 'Sólo', '_START_', 'utilizamos', 'only', 'We', 'use', 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.2, 0.1, 0.2, 0.0, 0.0, 0.0, 'ADV', 'RB', 9.0, 0.0, 'OK'] 
1

使用正則表達式來檢查字符串可以轉換爲float:

import re 

line = [float(x) if re.match("^\d+?\.\d+?$", x) else x for x in line]