Mik*_*e B 0 python dictionary tuples key list
我有以下字典,我想计算键出现的次数,字典是非常大的.
a = { (1,2):3, (1,3):5, (2,1):6 }
Run Code Online (Sandbox Code Playgroud)
我想要这个结果
1: 3 times
2: 2 times
3: 1 time
Run Code Online (Sandbox Code Playgroud)
使用itertools.chain
和collections.Counter
:
collections.Counter(itertools.chain(*a.keys()))
Run Code Online (Sandbox Code Playgroud)
或者:
collections.Counter(itertools.chain.from_iterable(a.keys()))
Run Code Online (Sandbox Code Playgroud)
>>> from collections import Counter
>>> a = { (1,2):3, (1,3):5, (2,1):6 }
>>>
>>> Counter(j for k in a for j in k)
Counter({1: 3, 2: 2, 3: 1})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1057 次 |
最近记录: |