2016-03-02 64 views
1

我想比较这两个名单:使用此方法串浮动错误

hexvalonsides = ['0.0', '0.3968708', '0.4124191', '0.5403639', '0.6150017', '0.8629506', '0.5946117', '0.4553542', '0.506171', '0.5026515', '0.0'] 
hexvalonsides = ['0.2505809', '0.247734', '0.0', '0.169306', '0.06264286', '0.3082903', '0.4218272', '0.4553542', '0.506171', '0.5026515', '0.0'] 

for i in range(0, len(hexvalonsides)): 
    for value in newhexvalonsides: 
     if float(hexvalonsides[i]) - 0.5 <= value <= float(hexvalonsides[i]) + 0.05: 
      count += 1 

不过,我不断收到一个错误ValueError: could not convert string to float: .我想这是因为在原始文件,我提取了列表,我手动输入了缺失数据的0.0值。不过,我不确定我在这里如何解决这个问题。我应该输入不同的0.0吗?有任何想法吗?

+0

你可以尝试运行:'import locale' 'locale._test()' – purpletentacle

+0

这是不可能的。你确定你执行了这两行吗? – purpletentacle

回答

1

新的答案:

检查您输入的数据。

只有这样,你可以得到以下错误消息:

ValueError: could not convert string to float: .

是当你有形式.

如String:

print float('.') 

输出:

ValueError: could not convert string to float: . 

OLD答:

这是工作在我身边:

hexvalonsides = ['0.0', '0.3968708', '0.4124191', '0.5403639', '0.6150017', '0.8629506', '0.5946117', '0.4553542', '0.506171', '0.5026515', '0.0'] 
newhexvalonsides = ['0.2505809', '0.247734', '0.0', '0.169306', '0.06264286', '0.3082903', '0.4218272', '0.4553542', '0.506171', '0.5026515', '0.0'] 

tmp = zip([ float(x) for x in hexvalonsides], 
      [ float(x) for x in newhexvalonsides]) 

count = sum(1 if x[0]-0.5 <= x[1] <= x[0]+0.05 else 0 for x in tmp) 

print count 
+0

我仍然给出了使用这种方法相同的错误。 – interstellar

+0

您是否使用了确切的代码或其他输入向量? – purpletentacle

+0

我实际上使用多个矢量输入(我在创建列表的for循环中运行上述代码)。但是,当我滚动列表时,看起来没有什么特别之处。 – interstellar

0

你需要转换value的浮动,以及:

for i in range(0, len(hexvalonsides)): 
    for value in newhexvalonsides: 
     if float(hexvalonsides[i]) - 0.5 <= float(value) <= float(hexvalonsides[i]) + 0.05: 
      count += 1 

虽然你可以做到这一点更优雅地使用map

import operator 

diff=map(operator.sub,map(float,hexvalonsides),map(float,newhexvalonsides)) 

print len(filter(lambda x:x>-0.5 and x<0.05,diff)) 
+0

即使我尝试将值转换为浮点数,我也会得到相同的错误。 – interstellar

+0

尽管它不应该有所作为,那么'import locale; locale.localeconv()['decimal_point']'返回什么? – Jaco

+0

你确定你没有'''而不是'0.0'。这是我可以重现错误的唯一方法,其他组合可以解析(例如'.0')或给出不同的错误(例如'0.0.0') – Jaco