2016-07-15 48 views
2

我正在使用openpyxl庫在電子表格中處理大量數據。優雅的方式來看看在Python中超過特定​​值的+/-範圍

我需要找到某些溫度值,然後根據該溫度查看其他單元。

問題是我的溫度在它的測量值有些波動,但我並不在意這一點。例如,如果我想查看25度外的數據,我真正想要的是大約24-26度的數據。我需要在很多溫度下做到這一點。

我知道如何在一個相當混亂的迭代的方式這樣做:

for num in [5,10,15,20,25]:  
    if temp > num -1 and temp < num + 1:   
     #do things 

但這只是感覺凌亂對我來說,有沒有清潔的方式做到這一點?比如檢查temp是否在num的某個錯誤之內?

回答

3

你現在有什麼是明確的; Python允許您鏈中的比較是這樣的:

for num in [5,10,15,20,25]:  
    if num - 1 <= temp <= num + 1:   
     #do things 

另一種方法是檢查之間的絕對之二:

for num in [5, 10, 15, 20, 25]: 
    if abs(num - temp) <= 1 

(如果temp是一個整數,你需要使用<=代替<表達與簡單的temp == num不同。)

0

您可以測試值在這樣的範圍內:

for num in [5,10,15,20,25]:  
    if num in range(24,27): 
     ... 

注意,如果輸入的數據是浮動這不起作用。 當然你也可以使用一些功能,你給它從一箇中心和最大距離產生此範圍:

def s_range(center, max_distance): # surrounding range 
    return range(center-max_distance, center+max_distance) 
... 
if num in s_range(25, 1): 
    ... 
2

如果你只是想適應你有一點點:

for num in range(5, 30, 5): 
    if abs(temp - num) < 1: 
     # do things 
0

對於這樣的事情,我寫了一個generic range comparison function,你可以很容易地在這裏使用擴展。雖然對於這種情況可能是過度的,但如果你有很多類似的檢查有不同的值,那麼這很有意義。

使用方法如下:

range_comparison(operator.lt, [25, True], 24) # returns True 
range_comparison(operator.lt, [25, True], 26) # returns None 

你用自己的功能結合本作更多的靈活性。

1

內置解決方案如何?你可以只使用isclose功能位於math(其可作爲的Python 3.5):

from math import isclose 

isclose(26, 25, abs_tol=1) 
Out[409]: True 

isclose(24, 25, abs_tol=1) 
Out[410]: True 

isclose(26.3, 25, abs_tol=1) 
Out[411]: False 

abs_tol信號的絕對容差(即差),以兩號被認爲是密切和isclose回到True

0

對於那些誰想要在Python 2.x中使用內置的功能,也有numpy.isclose()

from numpy import isclose as isclose 
a = 100.0 
b = 100.01 

print isclose(a,b, atol=0.02) # True 

從文檔:

對於有限值,isclose使用以下方程來測試兩個浮點值是否相等。

absolute(a - b) <= (atol + rtol * absolute(b)) 
相關問題