字符串浮动错误

时间:2016-03-02 16:35:04

标签: python list floating-point

我正在尝试比较这两个列表:

 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吗?有什么想法吗?

2 个答案:

答案 0 :(得分:2)

新答案:

检查您的输入数据。

唯一可以获得以下错误消息的方法:

ValueError: could not convert string to float: .

是指.

形式的字符串

示例:

print float('.')

输出:

ValueError: could not convert string to float: .

OLD ANSWER:

这对我很有帮助:

 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

答案 1 :(得分:1)

您还需要将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))