2015-06-03 43 views
0

我有下列项目列表:的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'}, 
] 
+0

你能否澄清 “大日”?你的意思是“最近的”? –

+0

按国家分组,然后从该组中取“最大日期” – Melon

+0

是最近的日期。因为我的数据非常庞大,什么才是复杂性最高的最有效的方法。 –

回答

3

使用循环并跟踪目前为止在每个国家/地区找到的最大值。你必须对那些日期解析为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'}] 
+0

谢谢你会检查出来 –

+0

我得到这个错误:ValueError:时间数据'%e-%% - %y'与格式'1-Mar-12'不匹配。任何想法为什么? –

+0

@Tarun:使用更新的版本;我在第一次修订中混淆了'strptime()'的参数。 –

0

你可以从1到12,然后分月名称映射到相应的号码每个国家的日期属性( - )并比较日期,月份和年份的数量。

0

或者在同一行:

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'])]