[問題] 請問字典功能

看板Python作者 (imagine)時間16年前 (2009/02/09 09:35), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串1/2 (看更多)
想請問一個有關dictionary的問題: 我有一份text 檔案,裡面含有多筆的email address(有些有重複相同的), 現在如果我想利用此份text file一次建立一個字典 而不是一個一個address輸入 並計算相同address出現的次數 請問該如何寫比較好 我的想法是每筆email看成一個key 我嘗試這樣寫: import string for line in infile: words= string.split (line) if len(words)>=2 and words[0]=="From": sec=words[1] #construct a new dictionary d={} #add one to the count if the email address existed d[sec]=d.get(sec,0)+1 #prints out the dictionary contents for key,values in d.items(): print key,values 但最後會出現 wpokf@pfok 1 sadoifj@dijf 1 sadoifj@dijf 1 wpokf@pfok 1 sadoifj@dijf 1 也就是他無法累加次數 不曉得是哪裡出了問題了.請高手幫忙解答 已經困了三天>.< 謝謝各位囉 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 24.11.127.26

02/09 10:38, , 1F
迴圈每跑一次字典就重新初始化,自然沒辦法累加次數
02/09 10:38, 1F
文章代碼(AID): #19ZuXbnu (Python)
討論串 (同標題文章)
文章代碼(AID): #19ZuXbnu (Python)