2012-09-13 73 views
0

我需要能夠存儲數據,一個是數字,一個是它出現的次數。我有一個for循環調用返回字典的方法:字典或列表?

for x in range(total_holidays): 
    t = trial() 
    y = y + "\n" + str(x+1) + "," + str(t["brown"]) + "," + str(t["rainbow"]) + "," + str(t["nothing"]) + "," + str(t["days"]) 
    total += t["days"] 
    #print total 
    if x%10000 == 0: 
     y0.append(y) 
     y = "" 

基本上我需要算多少次的T [「天」]發生,數量幾乎每一次變化。如果你想完整的代碼看這裏:

https://math.stackexchange.com/questions/193846/how-many-trials-would-you-expect-to-give-you-an-accurate-answer

所以,我會怎麼做,然後我需要後打印這一切。

y是csv文件的文本,總計用於計算平均值。


正如mgilson建議我應該使用這個?

from collections import Counter 

a = [] 
for x in range(total_holidays): 
    t = trial() 
    y = y + "\n" + str(x+1) + "," + str(t["brown"]) + "," + str(t["rainbow"]) + "," + str(t["nothing"]) + "," + str(t["days"]) 
    total += t["days"] 
    a.append(t['days']) 
    #print total 
    if x%10000 == 0: 
     y0.append(y) 
     y = "" 
z = Counter(a) 
print z 

我應該有這樣的事情嗎?

+1

你的代碼中有幾個位我不明白:例如,你檢查是否是Dr == 1 ',但儘可能接近我可以告訴'dr'永遠不會是1.它看起來像有兩個'db + = 1'這些行是有問題的。然而,不知道問題是什麼,很難知道你的代碼是否真的給出了正確的答案。 – DSM

+0

垃圾。沒有注意到。必須剛剛讀過其他行,並沒有想到。現在修復。 – FabianCook

+0

感謝那btw。將平均值從12.4改爲9.3 – FabianCook

回答

2

你想要什麼collections.Counter類型,dict亞型專門用於這樣的任務:

import collections 
days_occurred = collections.Counter() 

for ...: 
    t = trial() 
    days_occurred[t['days']] += 1 

# total is now sum(days_occurred.itervalues()) 

# you print the counts by iterating over the dict 

for days, count in days_occurred.iteritems(): 
    print "%d: %d" % (days, count) 
1

您不需要手動構建CSV文件。 Python已經有一個內置的模塊:

import csv 

writer = csv.writer(open('output.csv', 'wb')) 

# ... 

for x in range(total_holidays): 
    t = trial() 

    writer.writerow([x + 1, t['brown'], t['rainbow'], t['nothing'], t['days']]) 
    total += t['days'] 

除此之外,你的問題到底是什麼?

+0

嗯,我會使用它,我想要統計一個數字出現的次數,比如說讓trail()['days']返回'1,1,2,2,2,5,6,9,1 '我想要的東西告訴我'1 = 3,2 = 3,5 = 1,6 = 1,9 = 1' – FabianCook

+0

@SmartLemon - 如果是這種情況,可以使用'collections.Counter'來獲得它(這將返回一本字典) – mgilson

+0

請參閱編輯...我認爲這就是你的意思? – FabianCook