c = Counter('abcdeabcdabcaba')
with open("abc", 'w') as f:
for k,v in c.most_common():
f.write( "{} {}\n".format(k,v) )
有关Counter.most_common的帮助:
>>> Counter.most_common?
Docstring:
List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
我建议您使用
collections.Counter
,然后Counter.most_common
将执行您想要的操作:演示:
将其写入文件:
有关
Counter.most_common
的帮助:应该很好:)
字典没有计数器的顺序,因此如果您希望项目列表按某种顺序排序,则必须对其进行排序。。。在这种情况下,按“值”而不是“键”排序
相关问题 更多 >
编程相关推荐