我想创建一个 dictionary在 python 中自动计算其元素的重复次数:
当添加一个不包含的元素时,它应该插入相应的值 1,如果再次插入相同的元素,它将增加其计数器。
有没有比下面的更优雅/更紧凑的方式来实现这个字典?
if var in myList:
myDictionary[var] += 1
else:
myDictionary[var] = 1
请您参考如下方法:
用于计算元素 Counter是很棒的。
from collections import Counter
counted=Counter(iterable)
您可以像项目一样使用字典:
>>> myDict=dict(a=1,b=2,c=3)
>>> myDict
{'a': 1, 'c': 3, 'b': 2}
>>> Counter(myDict)
Counter({'c': 3, 'b': 2, 'a': 1})
或列表或其他可迭代对象:
>>> Counter('aabbccaabcaaa')
Counter({'a': 7, 'c': 3, 'b': 3})
为了澄清,你有:
if var in myDictionary: # loops over the KEYS of myDictionary
myDictionary[var] += 1
else:
myDictionary[var] = 1
假设 myDictionary 确实是一个字典,永远不会有任何重复;任何类型都只有一把 key 。
编辑
根据您的评论,字典理解很有用(Python 2.7 或 3+)
>>> myDict={'a':[1], 'b':[1,2], 'c':[1,2,3]}
>>> {k:len(v) for k, v in myDict.iteritems()}
{'a': 1, 'c': 3, 'b': 2}
使用默认字典:
>>> from collections import defaultdict
>>> dd=defaultdict(int)
>>> for k, v in myDict.iteritems():
... dd[k]=len(v)
...
>>> dd
defaultdict(<type 'int'>, {'a': 1, 'c': 3, 'b': 2})
计数器(使用列表理解):
>>> Counter([(k,len(v)) for k, v in myDict.iteritems()])
Counter({('a', 1): 1, ('b', 2): 1, ('c', 3): 1})
或者,只需使用带有生成器的 dict 构造函数:
>>> dict((k,len(v)) for k, v in myDict.iteritems())
{'a': 1, 'c': 3, 'b': 2}
最后一个,只是一个带生成器(或 lc)的直接 dict,在这种情况下可能是最“Pythonic”的。
