2014-07-09 46 views
1

我所需要的前10话和他们的数量,已经包含在字典中,按以下格式:顶部计数...返回输出的元组格式返回给字典格式

字计数(例如招呼10)

我有以下代码:

for word in word: 
      if word not in counts: 
        counts[word] = 1 
      else: 
        counts[word] += 1 

for word in counts: 
      top = sorted(counts.items()) 
      top_10 = top[:9] 
print top 

输出是与内部的元组的列表:[( '红',5),( '蓝色',2),( '绿色',1), ...]

但是,我需要它在f的ORMAT:

红5

蓝2

绿色1

如何才能做到这一点???

+0

你可以把你的单词列表在这里 –

回答

0

更换

print top 

for k,v in top: print k, v 
+1

好吧......甜......用Alfasin的“top_10”取代“top” – MJMV

1

首先,你可以用更少的(和更Python)统计代码:

for word in words: 
    count[word] = count.get(word,0) + 1 

其次,你可以达到你想要的打印格式:

for k in count: 
    print k,count[k] 

如果排序是你的问题,你可以使用operator.itemgetter()

from operator import itemgetter 
words = ['brown','yellow','red','blue','green','blue','green','blue','green'] 
count = {} 
for word in words: 
    count[word] = count.get(word,0) + 1 


top = sorted(count.iteritems(), key=itemgetter(1)) 
top_10 = top[-10:] 
print top_10 
+0

所以,如果我有不到10个字,它重复它们。有没有办法让它如此,以至于如果少于10个,它会返回存在的东西,排序? – MJMV

+0

@ user3814385这正是这个代码:) – alfasin

+0

下面是测试集的数据: resapi 1 埃及1 乐天1项 西马克1个 巴卡1 这是代码是什么打印: 巴卡1项 西马克1 巴卡1个 resapi 1 西马克1 巴卡1 resapi 1 乐天1 西马克1 巴卡1 resapi 1 埃及1 rakuten 1 simak 1 baca 1 重复的话,甚至不是在相同的顺序...为什么? – MJMV

0

您可以轻松地达致这使用Counter

from collections import Counter 
words = ['brown','yellow','red','blue','green','blue','green','blue','green'] 
c=Counter(words) 
for i,j in c.most_common(10): 
    print i,j 
+0

@ user3814385请点击这个http://repl.it/VH3你可以把你的单词列表 –