Reputation: 47
Add all the elements in the list of lists except the first element and make a new list.
l = [[u'Security', -604.5, -604.5, -604.5,
-302.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -2115.75],
[u'Medicare', -141.38, -141.38, -141.38, -70.69,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -494.83],
[u'Insurance', -338.0, -338.0, -338.0, -169.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1183.0]]
Output should look like
['total',-1083.88,-1083.88,-1083.88,-541.94,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,-3793.58]
Eg: -1083.88 of the output list is = -604.5+(-141.38)+(-338.0)=-1083.88
I've tried like this
for i in r:
del(i[0])
total = [sum(i) for i in zip(*r)]
Upvotes: 1
Views: 1776
Reputation: 36
If you want to be really efficient about it, you could use itertools' islice
from itertools import islice, repeat
s = map(sum, zip(*map(islice, l, repeat(1), repeat(None) ) ) )
total = ['total']
total.extend(s)
Edit: sorry, didn't read the entire context the first time around :)
Upvotes: 0
Reputation: 23524
To use all python flavour you need to use itertools.islice
since in Python zip()
returns iterator and you cannot just [1:]
subscript zip
object.
In [1]: l = [[u'Security', -604.5, -604.5, -604.5,
...: ...: -302.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -2115.75
...: ],
...: ...: [u'Medicare', -141.38, -141.38, -141.38, -70.69,
...: ...: 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -494.83],
...: ...: [u'Insurance', -338.0, -338.0, -338.0, -169.0, 0.0,
...: ...: 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1183.0]]
...:
In [2]: from itertools import islice
In [3]: total = [sum(new) for new in islice(zip(*l), 1, None)]
In [4]: total
Out[4]:
[-1083.88, -1083.88, -1083.88, -541.94, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -3793.58]
To include 'total'
in the begging as cᴏʟᴅsᴘᴇᴇᴅ kindly noted in comments
In [5]: ['total'] + total
Out[6]:
['total', -1083.88, -1083.88, -1083.88, -541.94, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -3793.58]
Upvotes: 2
Reputation: 402824
Going by your expected output, I believe you're looking for a transposition and sum on the columns. You can use zip
for that.
r = [sum(x) if not isinstance(x[0], str) else 'total' for x in zip(*l)]
print(r)
['total', -1083.88, -1083.88, -1083.88, -541.94, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -3793.58]
Alternatively, convert the transposal to a list
and you can avoid the if
check (this is similar to MaximTitarenko's answer, so credit to them as well).
r = [sum(x) for x in list(zip(*l))[1:]]
r.insert(0, 'total')
Or, if you'd prefer,
r = ['total'] + [sum(x) for x in list(zip(*l))[1:]]
Which is a little less elegant.
Upvotes: 5
Reputation: 886
You can try this:
result = ['total'] + [sum(el) for el in list(zip(*l))[1:]]
print(result)
# ['total', -1083.88, -1083.88, -1083.88, -541.94, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -3793.58]
Upvotes: 3