filifunk
filifunk

Reputation: 837

How to add up specific parts of a list?

I have a list with a bunch of data in the format of: date, month, data

I would like all of the entries with the same date to sum up all of their data and the output be simply date, data. In other words, the data looks something like this

[(1/1/2011, August, 5), (1/1/2011, July, 4), (1,1,2011, June, 1), (1/6/2011, December, 5)]

For this example I would want the output to be like this:

[(1/1/2011, 10), (1/6/2011, 5)]

How would I go about doing this? I know this would involve a for loop and if a date is similar it would sum up the data. But I'm stumped on how to go about this.

Upvotes: 2

Views: 182

Answers (3)

Tonechas
Tonechas

Reputation: 13723

Here is a one-liner based on itertools.groupby():

>>> from itertools import groupby
>>> from operator import itemgetter
>>> dates = [('1/1/2011', 'August', 5), ('1/1/2011', 'July', 4), 
             ('1/1/2011', 'June', 1), ('1/6/2011', 'December', 5)]
>>> [(date, sum(map(itemgetter(-1), group))) for (date, group) in groupby(dates, key=itemgetter(0))]
[('1/1/2011', 10), ('1/6/2011', 5)]

Notice that for this demo I used the same dates as in @alecrasmussen's answer as the data provided by the OP cannot be interpreted by Python.

Upvotes: 1

Alec
Alec

Reputation: 1469

Find all the dates in the list and then you can count each one:

dates = [('1/1/2011', 'August', 5), ('1/1/2011', 'July', 4),
         ('1/1/2011', 'June', 1), ('1/6/2011', 'December', 5)]

each_date = set(d[0] for d in dates)

count_dates = [(d, sum(i[2] for i in dates if i[0] == d)) for d in each_date]

print(count_dates)
# -> [('1/6/2011', 5), ('1/1/2011', 10)]

Upvotes: 1

Adam Hughes
Adam Hughes

Reputation: 16299

Use a dictionary to keep the unique dates:

dates = {}
for (date, month, day) in your_list:
    if date not in dates:
        dates[date] = day
    else
        dates[date] += day

You'd then have to go back to a list if you wanted the output as you've specified:

outlist = []
for (date, daycount) in dates.items():
    outlist.append( (date, daycount) )

That being said, whenever you're using dates, it's usually useful to store them as datetime objects and then operations like adding dates are more straightforward.

Upvotes: 2

Related Questions