c = Counter('abcdeabcdabcaba')
with open("abc") 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
的帮助:相关问题 更多 >
编程相关推荐