I have a list of tuples similar to this:
l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]
I want to create a simple one-liner that will give me the following result:
r = (25, 20) or r = [25, 20] # don't care if tuple or list.
Which would be like doing the following:
r = [0, 0]
for t in l:
r[0]+=t[0]
r[1]+=t[1]
I am sure it is something very simple, but I can't think of it.
Note: I looked at similar questions already:
How do I sum the first value in a set of lists within a tuple?
How do I sum the first value in each tuple in a list of tuples in Python?
I want to add something to the given answer:
If I have an array of dict e.g.
and i want to obtain two (or more) sums of calculated quantity over the values e.g. sum of quantities and of price*quantity
I can do:
Instead of:
Maybe the first solution is less readable, but is more "pythonesque" :)
Without using zip
Use
zip()
andsum()
:or:
timeit
results: