2016-03-02 61 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