2017-10-16 260 views
0

我有一個類型爲「string」的數值列表。一些在此列表中的元素有一個以上的值,例如:將列表內的字符串轉換爲浮點數

AF=['0.056', '0.024, 0.0235', '0.724', '0.932, 0.226, 0.634']

的另一件事是,一些元素可能是.

有了這樣說,我一直嘗試此列表中的元素轉換爲浮動(同時還節約元組,如果有一個以上的值),但我不斷收到以下錯誤:

ValueError: could not convert string to float: .

我試過的東西很多解決這個問題,用最新的一個是:

for x in AF: 
    if "," in x: #if there are multiple values for one AF 
     elements= x.split(",") 
     for k in elements: #each element of the sub-list 
      if k != '.': 
       k= map(float, k) 
       print(k) #check to see if there are still "." 
      else: 
       pass 

但是當我運行的是,我仍然得到同樣的錯誤。所以我從上面的循環中打印出k,果然,列表中仍然有.,儘管我聲明不要在字符串到浮點轉換中包含那些。

這是我想要的輸出: AF=[0.056, [0.024, 0.0235], 0.724, [0.932, 0.226, 0.634]]

+0

你能告訴你的期望的輸出? – CoryKramer

+0

@CoryKramer:增加了它 – claudiadast

+0

所以獨立的項目'.'應該被刪除? – RomanPerekhrest

回答

1
def convert(l): 
    new = [] 
    for line in l: 
     if ',' in line: 
      new.append([float(j) for j in line.split(',')]) 
     else: 
      try: 
       new.append(float(line)) 
      except ValueError: 
       pass 
    return new 

>>> convert(AF) 
[0.056, [0.024, 0.0235], 0.724, [0.932, 0.226, 0.634]] 
+0

由於忽略獨立'.'!當我嘗試時,我仍然得到'''Traceback(最近一次調用最後一個): File「VCF-to-hail-comparison.py」,line 320,in main() File「VCF-to-hail -comparison.py」,線路112,在主 轉換(AF) 文件 「VCF-to-hail-comparison.py」,第19行,在轉換 new.append([浮動(j)​​,其中在j行。分裂( 「」)) ValueError異常:無法將字符串轉換爲float:.''' – claudiadast

0

如果你試試這個:

result = [] 
for item in AF: 
    if item != '.': 
     values = list(map(float, item.split(', '))) 
     result.append(values) 

你得到:

[[0.056], [0.024, 0.0235], [0.724], [0.932, 0.226, 0.634]] 

可以簡化使用理解列表:

result = [list(map(float, item.split(', '))) 
      for item in AF 
      if item != '.'] 
0

隨着re.findall()功能(在擴展輸入列表):

import re 

AF = ['0.056', '0.024, 0.0235, .', '.', '0.724', '0.932, 0.226, 0.634', '.'] 
result = [] 

for s in AF: 
    items = re.findall(r'\b\d+\.\d+\b', s) 
    if items: 
     result.append(float(items[0]) if len(items) == 1 else list(map(float, items))) 

print(result) 

輸出:

[0.056, [0.024, 0.0235], 0.724, [0.932, 0.226, 0.634]] 
相關問題