2014-12-02 63 views
0

這需要在一個字典(字)創建對象的列表...注意,這是一個例子,字典大小不等的:從字典

{'wandered': [YearCount(year=2005, count=83769), YearCount(year=2006, count=87688), YearCount(year=2007, count=108634), YearCount(year=2008, count=171015)], 'request': [YearCount(year=2005, count=646179), YearCount(year=2006, count=677820), YearCount(year=2007, count=697645), YearCount(year=2008, count=795265)], 'airport': [YearCount(year=2007, count=175702), YearCount(year=2008, count=173294)]} 

然後我的函數返回列表在有序字計數對象從最頻繁到最高:

def wordFrequencies(words): 
    count = [] 
    for item, val in words.items(): 
     for i in val: 
      wc = createWordCount(str(item), int(i.count)) 
      count.append(wc) 
    newcount = count 
    newcount.sort(key = lambda x: x.count) 
    print(newcount) 

輸出:

[WordCount(word='wandered', count=83769), WordCount(word='wandered', count=87688), WordCount(word='wandered', count=108634), WordCount(word='wandered', count=171015), WordCount(word='airport', count=173294), WordCount(word='airport', count=175702), WordCount(word='request', count=646179), WordCount(word='request', count=677820), WordCount(word='request', count=697645), WordCount(word='request', count=795265)] 

但我什麼甲腎上腺素ED是減少從多到少頻繁的順序,每次前一個對象增加了前一計,而不是隻在一個新的對象添加字計數對象的列表,它應該是這樣的:

[WordCount(word=’request’, count=2816909), 
WordCount(word=’wandered’, count=451106), 
WordCount(word=’airport’, count=348996)] 
+0

YearCount是一個函數嗎? – 2014-12-02 16:27:20

+0

YearCount是保存年份和計數的對象 – MedaUser 2014-12-02 16:32:40

+0

您的意思是它應該是累積的? – 2014-12-02 16:34:18

回答

1
def wordFrequencies(words): 
    count = [] 
    for item, val in words.items(): 
     c = 0 
     for i in val: 
      c+=int(i.count) 
     wc = createWordCount(str(item), c) 
     count.append(wc) 
    newcount = count 
    newcount.sort(key = lambda x: x.count,reverse=True) 
    print(newcount)