2013-08-21 96 views
0
sub = [767220, 769287, 770167, 770276, 770791, 770835, 771926, 1196500, 1199789,1201485, 1206331, 1206467, 1210929, 1213184, 1213204, 1213221, 1361867, 1361921, 1361949, 1364886, 1367224, 1368005, 1368456, 1368982, 1369000, 1370365, 1370434, 1370551, 1371492, 1471407, 1709408, 1710264, 1710308, 1710322, 1710350, 1710365, 1710375] 

def runningMean(seq, n=0, total=0): #function called recursively 
    if not seq: 
     return [] 
    total = total + int(seq[-1]) 
    if int(seq[-1]) < total/float(n+1) * 0.9: # Check your condition to see if it's time to stop averaging. 
     return [] 
    return runningMean(seq[:-1], n=n+1, total=total) + [total/float(n+1)] 

avg = runningMean(sub, n = 0, total = 0) 
print avg #it prints the avg value which satisfies the above condition 

結果得到的是:要打印代碼列表?

[1710198.857142857, 1710330.6666666667, 1710344.0, 1710353.0, 1710363.3333333333, 1710370.0, 1710375.0] 

,但現在我需要打印滿足條件(在清單子段比平均中的項目,它打印更大的項目都平均&子列表平均現在我需要它來打印序列也是項目)

[1710198.857142857, 1710330.6666666667, 1710344.0, 1710353.0, 1710363.3333333333, 1710370.0, 1710375.0] 
[1709408, 1710264, 1710308, 1710322, 1710350, 1710365, 1710375] 

如何更改代碼WH ich將在Python中爲我提供這樣的結果?

+0

你說你要同時打印的平均和子滿足「條件」的列表。那究竟是什麼條件? – sgillis

+0

我不確定你在問什麼。它看起來像你的第二行只是子[30:]雖然 – Jean

+0

條件是(int(sub)> int(avg)* 0.9) –

回答

1

試試這個:

sub = [767220, 769287, 770167, 770276, 770791, 770835, 771926, 1196500, 1199789,1201485, 1206331, 1206467, 1210929, 1213184, 1213204, 1213221, 1361867, 1361921, 1361949, 1364886, 1367224, 1368005, 1368456, 1368982, 1369000, 1370365, 1370434, 1370551, 1371492, 1471407, 1709408, 1710264, 1710308, 1710322, 1710350, 1710365, 1710375] 
def runningMean(seq, n=0, total=0): #function called recursively 
    L = [[],[]] 
    if len(seq) == 0: 
     return L 
    total = total + int(seq[-1]) 
    if int(seq[-1]) < total/float(n+1) * 0.9: # Check your condition to see if it's time to stop averaging. 
     return L 
    NL = runningMean(seq[:-1], n=n+1, total=total) 
    L[0] += NL[0] + [total/float(n+1)] 
    L[1] += [seq[-1]] + NL[1] 
    return L 

avg = runningMean(sub, 0, 0) 
print(avg[0]) 
print(avg[1]) 

輸出:

[1710198.857142857, 1710330.6666666667, 1710344.0, 1710353.0, 1710363.3333333333, 1710370.0, 1710375.0] 
[1710375, 1710365, 1710350, 1710322, 1710308, 1710264, 1709408] 
0

Python可以從return multiple values的方法。您可以使用此,在每個返回調用您感興趣的元素

+0

當我返回seq它顯示整個列表不是隻是那些元素 –