[英]python: get the most frequent value in a list of dictionaries
我有這樣一個形狀的字典列表:
xs = [ { 'date': 1 }, { 'date': 1 }, { 'date': 2 }, { 'date': 1 }, { 'date': 4 }]
我需要獲取代表最多的日期,所有詞典中最受歡迎的日期
我的方法是:
例:
sorted_xs = sorted(xs, key=lambda x: x['date'])
ys = groupby(sorted_xs, lambda x: x['date'])
???
這不起作用(而且很丑):
max(list(groupby(sorted_xs, lambda x: x['date'])), key=lambda (k, x):len(list(x)))
您知道在python中更簡單和更具表現力的任何方法嗎?
使用collections.Counter()
對象對每個日期進行計數:
from collections import Counter
date_counts = Counter(d['date'] for d in xs)
most_common = {'date': date_counts.most_common(1)[0][0]}
我假設您想在此處再次以字典的形式獲取輸出,但是如果您只對日期值感興趣,則可以直接使用date_counts.most_common(1)[0][0]
。
演示:
>>> from collections import Counter
>>> xs = [{'date': 1}, {'date': 1}, {'date': 2}, {'date': 1}, {'date': 4}]
>>> date_counts = Counter(d['date'] for d in xs)
>>> {'date': date_counts.most_common(1)[0][0]}
{'date': 1}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.