从迭代器中填充计数字典

沃尔特·特罗斯

从迭代器填充计数字典的最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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章