如果元组具有相同的第一个元素,如何汇总元组列表中的元素? [英] how to aggregate elements of a list of tuples if the tuples have the same first element?

查看:164
本文介绍了如果元组具有相同的第一个元素,如何汇总元组列表中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,其中每个值都是一个元组列表.例如,这是我提取的键值:

I have a list in which each value is a list of tuples. for example this is the value which I extract for a key :

     [('1998-01-20',8) , ('1998-01-22',4) , ('1998-06-18',8 ) , ('1999-07-15' , 7), ('1999-07-21',1) ]

我也对列表进行了排序. 现在我想聚合这样的值:

I have also sorted the list. now I want to aggregate the values like this :

    [('1998-01' , 12 ) , ('1998-06' ,8 ) , ('1999-07',8 )]

从某种意义上说,我想按月对元组进行分组,将每个月的整数相加,我已经阅读了有关groupby的信息,我认为它对我的数据结构无济于事,因为我不知道该怎么做我将在列表中面对,所以我试图找到一种说法:如果i [0] [:6]相等,则从元组的第一个元素开始:sum i [1].但是我很难实现这个想法.

in some sense I want to group my tuples in terms of month , to sum the ints for each month together , I have read about groupby and I think it can't help me with my data structure because I have no idea what I'll be facing in my list so I'm trying to find a way to say : start from the first elements of the tuples if i[0][:6] are equal : sum i[1] . but I'm facing difficulty to implement this idea .

    for i in List :
        if i[0][:6] # *problem* I don't know how to say my condition :
        s=sum(i[1]) #?

如果我是python的新用户,我将不胜感激!

I would appreciate any advices as I'm a new user of python!

推荐答案

另一个答案与已经给出的答案不同.您可以简单地创建一个新字典,其中的键是年份-月份的组合.使用dictionary.get(key, defaultvalue)遍历列表中的日期可以解决问题. IT将当前值添加到新字典中的值中,如果该键尚不存在,它将返回默认值0并创建该键.

Yet another answer different from the ones given already. You can simpy create a new dictionary where the keys are the year-month combinations. A loop over the dates in your list + using dictionary.get(key, defaultvalue) should do the trick. IT adds the current value to the value in the new dictionary, if the key did not yet exist, it returns the default value 0 and creates the key.

data = [('1998-01-20',8) , ('1998-01-22',4) , ('1998-06-18',8 ) , ('1999-07-15' , 7), ('1999-07-21',1)]
dictionary = dict()
for (mydate, val) in data: #
    ym = mydate[0:7]    # the key is only the year month combination (i.e. '1998-01' for example)
    dictionary[ym] = dictionary.get(ym, 0) + val  # return the value for that key or return default 0 (and create key)

data_aggregated = [(key, val) for (key, val) in dictionary.iteritems()] # if you need it back in old format

这篇关于如果元组具有相同的第一个元素,如何汇总元组列表中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆