Re: [問題] 請問字典功能

看板Python作者 (我是沒牌的營養師!)時間16年前 (2009/02/09 10:52), 編輯推噓0(005)
留言5則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《drlo (imagine)》之銘言: : 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 我只幫原來的程式碼調整了一下位置跟縮排.. import string infile = ['From www@xx.com.tw', 'From www@xx.com.tw', 'From jj@cc.com.tw'] d={} for line in infile: words= string.split (line) if len(words)>=2 and words[0]=="From": sec=words[1] d[sec]=d.get(sec,0)+1 for key,values in d.items(): print key,values 試試看吧 :) (應該有更易讀的寫法才是) -- 誠徵PHP網站工程師,熟MVC架構 http://blog.eddie.com.tw/ 全職、兼職可,意者請敲 :) http://www.eddie.com.tw/ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.132.128.37

02/09 11:38, , 1F
太感謝了,跑得出來,不過這個結果呈現只有最後累加數字,
02/09 11:38, 1F

02/09 11:42, , 2F
即使是相同位址,但還是會呈現目前累計的數字,該怎麼改寫呢ꤠ
02/09 11:42, 2F

02/09 12:12, , 3F
在第一個for裡的最後一行print words[1], d[sec]
02/09 12:12, 3F

02/09 12:13, , 4F
最後面的for就不用了
02/09 12:13, 4F

02/09 13:29, , 5F
感謝aquarianboy的解答,我悶了幾天總算跑得出來了..:)
02/09 13:29, 5F
文章代碼(AID): #19Zvg4tS (Python)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
文章代碼(AID): #19Zvg4tS (Python)