Dio*_*lor 3 python dictionary python-collections
我使用了文档中的示例:
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
Run Code Online (Sandbox Code Playgroud)
我怎样才能得到结果:
{ 'a': 5, 'r' :2 , 'b' :2}
Run Code Online (Sandbox Code Playgroud)
假设我们想保留Counter().most_common()
代码?
小智 6
dict
会很容易做到这一点:
>>> dict(Counter('abracadabra').most_common(3))
{'a': 5, 'r': 2, 'b': 2}
>>>
Run Code Online (Sandbox Code Playgroud)
为了进一步参考,这里是返回的部分内容help(dict)
:
dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
Run Code Online (Sandbox Code Playgroud)
最简单的方法就是简单地使用 dict()
dict(Counter('abracadabra').most_common(3))
Run Code Online (Sandbox Code Playgroud)
输出:
{'a': 5, 'r': 2, 'b': 2}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2101 次 |
最近记录: |