Python list group and sum with more fields

后端 未结 4 514
情深已故
情深已故 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:40

    I would use a dictionary to keep track of like first entries, as so:

    my_dict = {}
    for entry in myList:
        if entry[0] not in my_dict:
            #This makes my_dict hold dates as keys and a list of 2 integers as values
            my_dict[entry[0]] = [entry[1:]]
        else:
            #In the case that the date is already in my_dict, add the new integers
            my_dict[entry[0]][0] += entry[1]
            my_dict[entry[0]][1] += entry[2]
    #Now my_dict holds dates as keys with all the sums following
    #If I really need it to be in the list format you asked for:
    sumList = []
    for value in my_dict:
        sumList.append(value, my_dict[value][0], my_dict[value][1])
    

提交回复
热议问题