Python list group and sum with more fields

后端 未结 4 553
情深已故
情深已故 2021-01-26 05:08

I have a list with two integer fields which I would like to sum (string,integer, integer)

myList= [[[\"26-07-2017\",2,0], [\"26-07-2017\",3,0], [\"27-07-2017\",         


        
4条回答
  •  没有蜡笔的小新
    2021-01-26 05:41

    You can use dict to store your unique dates and sum of the values

    Code:

    myList= [[["26-07-2017",2,0], ["26-07-2017",3,0], ["27-07-2017",1,0], ["27-07-2017",0,1]]]
    dic = {}
    for x in myList[0]:
        try:
            dic[x[0]][0] = dic[x[0]][0]+x[1]
            dic[x[0]][1] = dic[x[0]][1] + x[2]
        except:
            dic[x[0]] = [x[1], x[2]]
    [[k,v[0], v[1]]for k,v in dic.items()]
    

    Output:

    [['26-07-2017', 5, 0], ['27-07-2017', 1, 1]]
    

提交回复
热议问题