Python:获取唯一键的最大值对象



我有以下项目列表:

[
    {'country' : 'India', 'date' : '18-Mar-14'},
    {'country' : 'India', 'date' : '18-Apr-14'},
    {'country' : 'India', 'date' : '18-May-14'},
    {'country' : 'Australia', 'date' : '18-Mar-14'},
    {'country' : 'Australia', 'date' : '18-Apr-14'},
    {'country' : 'Australia', 'date' : '18-May-14'},
    {'country' : 'China', 'date' : '18-Mar-14'},
    {'country' : 'China', 'date' : '18-Apr-14'},
    {'country' : 'China', 'date' : '18-May-14'}
]

我如何才能只获得包含每个国家最大日期值的项目,即对于每个国家,它返回包含该国家最大日期的项目。在本例中,结果列表将是:

[
    {'country' : 'India', 'date' : '18-May-14'},
    {'country' : 'Australia', 'date' : '18-May-14'},
    {'country' : 'China', 'date' : '18-May-14'},
]

使用循环并跟踪到目前为止每个国家找到的最大值。您必须将这些日期解析为datetime对象,以便您可以轻松地比较它们:

from datetime import datetime
max_dates = {}
for entry in list_of_dicts:
    date = datetime.strptime(entry['date'], '%d-%b-%y')
    country = entry['country']
    if country not in max_dates or date > max_dates[country][0]:
        max_dates[country] = (date, entry)
result = [entry for date, entry in max_dates.values()]
演示:

>>> from datetime import datetime
>>> list_of_dicts = [
...     {'country' : 'India', 'date' : '18-Mar-14'},
...     {'country' : 'India', 'date' : '18-Apr-14'},
...     {'country' : 'India', 'date' : '18-May-14'},
...     {'country' : 'Australia', 'date' : '18-Mar-14'},
...     {'country' : 'Australia', 'date' : '18-Apr-14'},
...     {'country' : 'Australia', 'date' : '18-May-14'},
...     {'country' : 'China', 'date' : '18-Mar-14'},
...     {'country' : 'China', 'date' : '18-Apr-14'},
...     {'country' : 'China', 'date' : '18-May-14'}
... ]
>>> max_dates = {}
>>> for entry in list_of_dicts:
...     date = datetime.strptime(entry['date'], '%d-%b-%y')
...     country = entry['country']
...     if country not in max_dates or date > max_dates[country][0]:
...         max_dates[country] = (date, entry)
... 
>>> [entry for date, entry in max_dates.values()]
[{'date': '18-May-14', 'country': 'China'}, {'date': '18-May-14', 'country': 'Australia'}, {'date': '18-May-14', 'country': 'India'}]

您可以将月份名称映射为从1到12的相应数字,然后用(-)分割每个国家/地区的日期属性,并比较日、月和年的数字。

或者一行:

from itertools import groupby
from datetime import datetime
[(x,max(y,key=lambda o:datetime.strptime(o['date'], '%d-%b-%y'))) for x,y in groupby(sorted(t, key=lambda o: o['country']), key=lambda o: o['country'])]

最新更新