从迭代器填充计数字典的最pythonic方法是什么?
我知道有collections.Counter
,我可以做
counter = Counter(iterable)
然后counter
就像字典一样使用字典,这些字典的不同项iterable
和项的值作为键。
但是必须有一种Python的方法来与常规对象做相同的事情,dict
比常规的方法更紧凑
count = {}
for item in iterable:
if item not in count:
count[item] = 1
else:
count[item] += 1
它是什么?
一种简单的方法:
count = {}
for item in iterable:
count[item] = count.get(item, 0) + 1
但通常,您应该只使用collections.Counter
。您不会使用Counter
“就像”字典一样,而是一个字典。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句