Reputation: 255
I have a list like this:
[(u'a', 0, 25), (u'a', 1, 11), (u'a', 3, 60), (u'a', 4, 89), (u'b', 0, 18),
(u'b', 1, 76), (u'b', 2, 52), (u'b', 3, 75), (u'b', 4, 46)]
I would like to take 0th element from both a and b, multiply them, add it to a sum variable. If one item is missing in a or b (in this example a[2]), then it will be denoted as 0.
My approach:
But the problem is I cannot assign 0 to the index which does not exist(like a[2]). Any solution or easier method to do this?
Upvotes: 0
Views: 137
Reputation: 133544
data = [(u'a', 0, 25), (u'a', 1, 11), (u'a', 3, 60), (u'a', 4, 89), (u'b', 0, 18),
(u'b', 1, 76), (u'b', 2, 52), (u'b', 3, 75), (u'b', 4, 46)]
d = {'a': {}, 'b': {}}
for x, y, z in data:
d[x][y] = z
>>> sum(d['a'].get(k, 0) * d['b'].get(k, 0)
for k in d['a'].viewkeys() | d['b'].viewkeys())
9880
Upvotes: 1