Jyotiska
Jyotiska

Reputation: 255

Python Multiplication within a List

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:

  1. Take two empty lists a_list and b_list.
  2. Iterate over the big list and based on the first item ('a' or 'b') put the item in respective list.
  3. Pick each item based on same index from both list, multiply them and put it in sum variable.
  4. Continue to the end of list.

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

Answers (1)

jamylak
jamylak

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

Related Questions