I have a nested list like the one below, for which I'm trying to sum the values of column 1 related with the same value in column 2, and add the a new sublist with the sum and another sublist with "Total".
a = [
['45', '00128'],
['88', '00128'],
['87', '00128'],
['50', '88292'],
['69', '88292'],
['70', '72415'],
['93', '72415'],
['79', '72415']
]
My current code is like below, for which I suppose that would be operating something over list a, but is not changing anything within a.
for sl in a:
x = sl[1]; c0=0
if (sl[1] == x):
c0 = c0 + int(sl[0])
else:
a.insert(a.index(sl)+1,[c0,''])
a.insert(a.index(sl)+2,['Total',''])
The output I'm looking for is like this:
b = [
['45', '00128'],
['88', '00128'],
['87', '00128'],
['220', ''], # This is 45 + 88 + 87
['Total', ''],
['50', '88292'],
['69', '88292'],
['119', ''], # This is 50 + 69
['Total', ''],
['70', '72415'],
['93', '72415'],
['79', '72415'],
['242', ''], # This is 70 + 93 + 79
['Total', '']
]
How to do this? thanks
UPDATE
Input list with 4 columns like one to the left and needed to sum col1, col3 and col4 to get the one to the rigth.
a = [ >> b = [
['45', '00128', '2','4'], >> ['45', '00128', '2', '4' ],
['88', '00128', '1','3'], >> ['88', '00128', '1', '3' ],
['87', '00128', '4','0'], >> ['87', '00128', '4', '0' ],
['50', '88292', '1','1'], >> ['220', '' , '7', '7' ],
['69', '88292', '9','5'], >> ['Total', '', 'Total', 'Total'],
['70', '72415', '8','9'], >> ['50', '88292', '1', '1' ],
['93', '72415', '3','2'], >> ['69', '88292', '9', '5' ],
['79', '72415', '5','7'] >> ['119', '', '10', '6' ],
] >> ['Total', '', 'Total', 'Total'],
>> ['70', '72415', '8', '9' ],
>> ['93', '72415', '3', '2' ],
>> ['79', '72415', '5', '7' ],
>> ['242', '', '16', '18' ],
>> ['Total', '', 'Total', 'Total'],
>> ]