list - python: Datatable add row and column total -


i have datatable in format of multi list following, want add row total , column total, need sum of integer values , append string values.

[[["type",""],["april",""],["may",""]],  [["red",""],[15 , "item3,item9"] [9 , "item7,item3"]],  [["blue",""],[7 , "item7,item8"] [2 , "item1,item8"]],  [["green",""],[10 , "item5,item8"] [7 , "item3,item7"]] ] 

after adding column & row sum table above table

[[["type",""],["april",""],["may",""],["rowtotal",""]],  [["red",""],[15 , "item3,item9"] [9 , "item7,item3"],[24,"item3,item7,item9"]],  [["blue",""],[7 , "item7,item8"] [2 , "item1,item8"]],[9,"item1,item7,item8"],  [["green",""],[10 , "item5,item8"] [7 , "item3,item7"],[17,"item3,item5,item7"]]  [["total",""],[32 , "item5,item8"] [18 , "item3,item7"],[50,"item3,item5,item8"]] ] 

how add in more efficient way using python?

use reduce,i have example you.

from functools import reduce table = [[["type",""],["april",""],["may",""]],  [["red",""],[15 , "item3,item9"], [9 , "item7,item3"]],  [["blue",""],[7 , "item7,item8"], [2 , "item1,item8"]],  [["green",""],[10 , "item5,item8"] ,[7 , "item3,item7"]] ] def helper(x,y):     return [x[0]+y[0],x[1]+y[1]] line in table[1:]:     line.append(reduce(helper,line[1:])) table.append([reduce(helper,(table[i][j] in range(1,4) )) j in range(1,len(table))]) table[0].append(["rowtotal",""]) table[-1].insert(0,["total",""]) line in table:     print(line) 

the new answer,maybe should use map

def helper(x,y):     return [x[0]+y[0],x[1]+y[1]] def colum(x,y):     return [helper(x[i],y[i]) in range(len(x))] line in table[1:]:     line.append(reduce(helper,line[1:])) table.append(reduce(colum,table[1:])) table[0].append(["rowtotal",""]) table[-1][0]=["total",""] line in table:     print(line) 

Comments