簡體   English   中英

在 python 中,如何將兩個列表列表相互分割?

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

我有兩個這樣的列表

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,等等。謝謝您的幫助?

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

或者不是那么漂亮,但是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM