Skip to content

Instantly share code, notes, and snippets.

@brianspiering
Created November 25, 2014 15:56
Show Gist options
  • Save brianspiering/f614020ff0c5589a2bcb to your computer and use it in GitHub Desktop.
Save brianspiering/f614020ff0c5589a2bcb to your computer and use it in GitHub Desktop.
Sum the events for each day using the reduce algorithm.
# Sum the events for each day using the reduce algorithm.
from itertools import groupby
from operator import itemgetter
logs = [('2009-09-02', 11),
('2009-09-02', 3),
('2009-09-03', 10),
('2009-09-03', 4),
('2009-09-03', 22),
('2009-09-06', 33),
('2009-09-02', 13),
('2009-09-03', 15)]
for key, entries in groupby(sorted(logs), itemgetter(0)): # Group by 1st element in tuple
print key, sum(entry[1] for entry in entries) # Sum 2nd element in tuple
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment