在python中,如何将两个列表列表相互划分?

时间:2011-06-29 18:55:38

标签: python list

我有两个像这样的列表

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

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

我想把第二个元素相互分开。 (在这种情况下,我想将3440除以85,将82除以913,依此类推。感谢您的帮助?

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:-1)

或者不那么漂亮但是:

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)

根据评论编辑为更加pythonic(注意Sven的解决方案已被选为基础):

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)))]