2017-02-16 101 views
-3

我想知道平均價格在一定範圍內保持多久。讓說我的值是:如何計算列表中的平均時間長度

[10, 7.7, 9.5, 15, 8.8, 9.3, 7.7, 16] 

例如,如果值是8之間 - 9.9,多久平均之前,它是> 14(不倒退)?

9.5在1天內通過14次。在3天內8.8。 9.3在2天內。在1天7.7。所以平均值是(1 + 3 + 2 + 1)/ 4 = 1.75天。

我想創建一個程序,爲我做這個計算,但我有問題。

代碼:

list = [10, 7.7, 9.5, 15, 8.8, 9.3, 7.7, 16] 

def new_function() 
    for i in list: 

    while 8 < x < 9.99 (store index position as initial y); 

    when x becomes > 14 (take index position and subtract it from initial y to find length) 

    repeat for next i where 8 < x < 9.9 

average = sum(length)/len(length) 
print(average) 
+0

你能提供在CSV文件中的數據(10行左右)的樣本?這將使您更容易理解您的需求並幫助驗證推薦的解決方案。 – Apollo2020

+0

這些數字與我在列表中提供的值非常相似。我只是用這些數字來簡化事情。 2欄:日期和價格。數千行數據。謝謝你的幫助 –

回答

0

保留一個計數器在每個條目列表,一旦開始進入被發現,直到你到達一個> 14。此時將找到的值添加到總計並重置運行。此外,每次添加一個到每個櫃檯周圍循環,如下所示:

data = [10, 7.7, 9.5, 15, 8.8, 9.3, 7.7, 16] 
run = [] 
total_days = 0 
total_entries = 0 

for value in data: 
    if value > 14: 
     total_days += sum(run) 
     total_entries += len(run) 
     run = [] 
    elif 8 < value < 9.99 or len(run): 
     run.append(0) 
    run = [value + 1 for value in run] 

print total_days/float(total_entries) 

給你:

1.75