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,开发者_StackOverflow 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?
from __future__ import division
quotients = [x[1] / y[1] for x, y in zip(list1, list2)]
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)))]
精彩评论