簡體   English   中英

在django python中計算dict列表中的重復項

[英]Count the duplicates in list of dict in django python

如何在此列表中找到重復項的計數。

>>> result = SiteTags.objects.values('content_type','object_id')
>>> result
[{'object_id': 1, 'content_type': 46}, {'object_id': 1, 'content_type': 46}, {'object_id': 2, 'content_type': 42}]

無論如何在查詢中找到? 或通過其他方式?

謝謝!

如果我正確理解您的請求, collections.Counter將是計算重復項的有用方法。 它僅適用於hashable輸入,因此列表中的字典需要轉換為已排序項的元組:

>>> from collections import Counter
>>> Counter([tuple(sorted(d.items())) for d in result])
Counter({(('content_type', 46), ('object_id', 1)): 2, (('content_type', 42), ('object_id', 2)): 1})

可能不言而喻,重復項是計數大於一的條目:-)

set(tuple(sorted(r.iteritems())) for r in result)

為您提供此列表中的一組唯一元素。 取其長度並將其與len(result)進行比較。

要在結果中獲取每個元素及其計數:

counter = {}
for r in result:
    tup = tuple(sorted(r.iteritems()))
    counter[tup] = counter.get(tup, 0) + 1
for tup, cnt in counter.iteritems():
    print dict(tup), cnt

打印:

{'object_id': 2, 'content_type': 42} 1
{'object_id': 1, 'content_type': 46} 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM