我需要以下列格式包含在字典中的前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
输出是一个里面有元组的列表:[('red',5),('blue',2),('green',1),...]
但是,我需要格式为:
红色5
蓝色2
绿色1
如何做到这一点?
答案 0 :(得分:1)
首先,您可以使用更少(和更多pythonic)代码:
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
答案 1 :(得分:0)
替换
print top
与
for k,v in top: print k, v
答案 2 :(得分: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