繁体   English   中英

字典列表 - 计数出现次数

[英]List of dict - count occurences

我正在努力实现,

前:

dict = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}, {'name':'count', 'label':'Count1'}]

后:

dict = [{'name':'count', 'label':'Count', 'count': 2},{'name':'type', 'label':'Type', 'count': 1}]

尝试使用时:

from collections import Counter
Counter(dict)

它抛出TypeError: unhashable type: 'dict'

好吧,dict 不能是 Counter 的键。 因为它是可变的。 您需要将您的 dict 转换为不可变类型。 示例:

from collections import Counter
Counter(frozenset(d.items()) for d in dict)

注意:您的代码似乎是错误的。 最后一个字典中的“计数”后面有一个“1”。

下面的代码将有所帮助

dict=list({v['name']:v for v in [i for i in dict if i.update({'count':[a['name'] for a in dict].count(i['name'])})==None]}.values())

Counter的解决方案,虽然不是很pythonic:

from collections import Counter
d = [{'name': 'count', 'label': 'Count'}, {'name': 'type', 'label': 'Type'}, {'name': 'count', 'label': 'Count'}]

r = [dt.update({'count': count}) or dt for sub, count in Counter(map(lambda i: tuple(i.items()), d)).items() for dt in [dict(sub)]]

r 是:

[{'name': 'count', 'label': 'Count', 'count': 2}, {'name': 'type', 'label': 'Type', 'count': 1}]

暂无
暂无

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

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