| home | about me | feed RSS feed

from datetime import date
from itertools import groupby
import operator

L = [(1,'spam',date(2010,1,1)),(2,'spam',date(2010,1,2)), 
     (3,'eggs',date(2010,1,2)),(4,'eggs',date(2010,1,1)), 
     (5,'cheese',date(2010,1,1))]

""" groupwise maximum 
    sort by date in descending order, then by grouping item
"""
L.sort(key=operator.itemgetter(2), reverse=True)
L.sort(key=operator.itemgetter(1))

for key, group in groupby(L, key=operator.itemgetter(1)):
    for item in group:
        # first item is tuple with maximum date
        print item
        break
#(5, 'cheese', datetime.date(2010, 1, 1))
#(3, 'eggs', datetime.date(2010, 1, 2))
#(2, 'spam', datetime.date(2010, 1, 2))

""" groupwise minimum
    sort by grouping item, and date in ascending order
"""
L.sort(key=operator.itemgetter(1,2))

for key, group in groupby(L, key=operator.itemgetter(1)):
    for item in group:
        # first item is tuple with minimum date
        print item
        break
#(5, 'cheese', datetime.date(2010, 1, 1))
#(4, 'eggs', datetime.date(2010, 1, 1))
#(1, 'spam', datetime.date(2010, 1, 1))

For all of your Python sorting questions, start here: http://wiki.python.org/moin/HowTo/Sorting/

tags: python
created: 2010-05-21 | updated: 2010-06-07


Comments are now closed for this post.