简体   繁体   English

如何将列表的特定部分加起来?

[英]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 我有一个包含一堆数据的列表,格式为: 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. 我知道这会涉及到for循环,如果日期相似,它将对数据进行汇总。 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. 话虽如此,无论何时使用日期,通常将它们存储为datetime对象都是很有用的,然后像添加日期这样的操作就更简单了。

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() : 这是基于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. 请注意,在此演示中,我使用了与@alecrasmussen答案相同的dates因为OP无法提供Python解释的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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