Fred Wilson
Fred Wilson

Reputation: 23

In python, how to divide two lists of lists by each other?

I have two lists like so

volB = [(Tarp, 3440, 7123), (Greg, 82, 1083)]

and

# 500B = [(Tarp, 85, 203), (Greg, 913, 234)]
B500 = [(Tarp, 85, 203), (Greg, 913, 234)]

I want to divide the second elements by each other. (In this case, I'd want to divide 3440 by 85, 82 by 913, and so on. Thanks for the help?

Upvotes: 1

Views: 3345

Answers (2)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29103

OR not so beatiful but:

lA = [('A',123,11),('B', 1, 11)]
lB = [('B',12,11),('A', 1, 11)]

res = {}

for x,y,z in (lA+lB):
    if not x in res:
        res[x] = y
        continue
    res[x] = res[x] / (y * 1.0)

Edited as per comment to be more pythonic (note that Sven's solution has been selected as base):

from operator import itemgetter

lA = [('A',123,11),('B', 1, 11)]
lB = [('B',12,11),('A', 1, 11)]

[float(x[1])/float(y[1]) for x,y in zip(sorted(lA,key=itemgetter(0)), sorted(lB,key=itemgetter(0)))]

Upvotes: -1

Sven Marnach
Sven Marnach

Reputation: 601619

from __future__ import division
quotients = [x[1] / y[1] for x, y in zip(list1, list2)]

Upvotes: 7

Related Questions