簡體   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