简体   繁体   中英

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM