Suppose I have the following list tuples:
myList = [(0,2),(1,3),(2,4),(0,5),(1,6)]
I want to sum this list based on the same first tuple value:
[(n,m),(n,k),(m,l),(m,z)] = m*k + l*z
For myList
sum = 2*5 + 3*6 = 28
How can I got this?
Suppose I have the following list tuples:
myList = [(0,2),(1,3),(2,4),(0,5),(1,6)]
I want to sum this list based on the same first tuple value:
[(n,m),(n,k),(m,l),(m,z)] = m*k + l*z
For myList
sum = 2*5 + 3*6 = 28
How can I got this?
This solution does it in a single pass as opposed to the more readable
defaultdict
version which takes two passes and may take more space:You can use
collections.defaultdict
:With below program even if you have multiple entries and not only two for same key, it will work