简体   繁体   English

增加 defaultdict 列表的计数

[英]Increment count on defaultdict list

How to increment the count in defaultdict of list like如何在列表的defaultdict中增加计数,例如

import collections
dict = collections.defaultdict(list)

dict["i"][0]+=1 throws a type error. dict["i"][0]+=1抛出类型错误。

I am expecting the dict to be like我期待 dict 像

{"i":[1,]}

Any efficient approach for this instead of using any loops statements?任何有效的方法而不是使用任何循环语句?

import collections

s = collections.defaultdict(lambda: [0])

s['i'][0] += 1

You need to retrieve the item from the dict and then appending to it您需要从字典中检索项目,然后附加到它

d = collections.defaultdict(list)
d['i'].append(1)

>>> d
defaultdict(<type 'list'>, {'i': [1]})

Also don't use dict as a variable name, it is used to construct dicts.也不要使用dict作为变量名,它用于构造 dicts。

>>> type(dict)
<type 'type'>

You can use Counter from collections您可以使用集合中的Counter

from collections import Counter
c = Counter()
sample_list = ['a','b','c','a','b','d','e','b']
for l in sample_list:
    c[l] += 1

Now the variable c would give the following,现在变量c将给出以下内容,

>>>Counter({'a': 2, 'b': 3, 'c': 1, 'd': 1, 'e': 1})

You can get count of each element as follows:您可以按如下方式获取每个元素的计数:

c['a']
>>>2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM