2016-02-12 63 views
1

最接近的值我有以下陣列:如何找到陣列

y_new = [0.0057602140000000005, nan, nan, nan, nan, nan, 0.0057104540000000002, nan, 0.0056821390000000001, nan, nan, nan, nan, nan, nan, 0.0056911319999999998, nan, nan, nan, nan, nan, 0.0054902060000000001, nan, nan, nan, nan, nan, nan, 0.0053461740000000004, nan, nan, nan, nan, 0.0055180319999999991, nan, nan, nan, nan, nan, nan, nan, 0.0051784170000000003, nan, nan, nan, nan, nan, nan, 0.0051544399999999997, nan, nan, nan, nan, nan, nan, 0.005136781, nan, nan, 0.0051989519999999997, nan, nan, nan, nan, nan, nan, 0.0051330490000000006, 0.0052893050000000002, nan, nan, nan, nan, nan, nan, nan, 0.0053077380000000002, nan, nan, nan, nan, 0.0053766209999999998, 0.0053431900000000003, nan, nan, nan, nan, 0.0051352960000000001] 

我想選擇陣列中的一個隨機點,並制定出離這裏最近的真正價值是高於還是低於它。非實數值是「南」,真實值是數字。然後我想計算這兩點之間的差異,其中y_new[5]y_new[6]之間的差異僅爲1天。

任何想法?

+0

這似乎很簡單。所以要麼我錯過了一些關鍵信息,或者你還沒有嘗試過。我希望假設前者? – James

+0

這個「1天」來自哪裏?我在這裏沒有看到任何日期。 – Matthias

回答

0

我不是一個python程序員,但我認爲類似的東西會給你你想要的東西。

randomIndex = 5; 
sizeofArray = 200; 
lessThan = 0; 
greaterThan = 0; 

for(int i = randomIndex; i >=0; i---) 
{ 
value = y_new[i]; 
if(value != nan) 
{ 
lessThan = i; 
return; 
} 

} 

for(int i = randomIndex; i <sizeOfArray; i++) 
{ 
value = y_new[i]; 
if(value != nan) 
{ 
greaterThan = i; 
return; 
} 

} 

less = randomIndex - lessThan; 
great = greaterThan - randomIndex; 

if(less < great) return less; 
else return great 
+0

用於初始生成'randomIndex'和'sizeofArray'使用'randomIndex = Random()。nextInt(sizeofArray)'和'sizeofArray = len(y_new)' – James

+0

謝謝你,請放心! 我完全不熟悉編碼,所以試圖學習。 @james –

+0

@CharlesHolroyd如果你是這個新人,仍然在使用這個級別的算法,我會推薦學習實現排序算法。插入排序作爲一個很好的入門者,但是然後嘗試實現合併和選擇排序,而不是看它的僞代碼,只是算法的基本描述。此外,由於您正在使用python進行學習,因此可以使用turtle模塊進行學習,因爲它可以讓您直觀地查看代碼正在使用的路徑。用它學習如何利用遞歸和迭代來創建複雜的模式。 – James

0

這是我覺得最Python的方式去...

假設指數作爲隨機指標, y_new陣列簡化, 的伎倆會被分割你的列表(片) 並找到正常和反轉列表中的下一個實數。 然後以天爲單位求出找到三角洲的指數。 希望它有幫助。

這裏有一個簡單的代碼:

index=4 
y_new = [0.1, 'nan', 'nan', 0.2, 'nan','nan', 0.3,'nan'] 

nextList=y_new[index:] 
beforeList=y_new[:index] 

before_idx=(i for i,v in enumerate(list(reversed(beforeList))) if v!='nan').next()  
next_idx=(i for i,v in enumerate(nextList) if v!='nan').next()  

print y_new 
print before_idx 
print next_idx 

print "interval between 2 real number near index %d is: %d days" %(index,(next_idx+before_idx+1))