2017-10-16 152 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]] 
相关问题