sha*_*nuo 28 python dictionary
如何从字典中查找前3个列表?
>>> d
{'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4}
Run Code Online (Sandbox Code Playgroud)
预期结果:
and: 23
only: 21
this: 14
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 41
>>> d = Counter({'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4})
>>> d.most_common()
[('and', 23), ('only.', 21), ('this', 14), ('test', 4), ('a', 2), ('is', 2), ('work', 2), ('will', 2), ('as', 2)]
>>> for k, v in d.most_common(3):
... print '%s: %i' % (k, v)
...
and: 23
only.: 21
this: 14
Run Code Online (Sandbox Code Playgroud)
计数器对象提供了各种其他优点,例如,首先收集计数几乎是微不足道的.
Mar*_*ina 21
>>> d = {'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4}
>>> t = sorted(d.iteritems(), key=lambda x:-x[1])[:3]
>>> for x in t:
... print "{0}: {1}".format(*x)
...
and: 23
only.: 21
this: 14
Run Code Online (Sandbox Code Playgroud)