通过同时迭代2个嵌套列表来计算值

时间:2013-05-05 21:30:50

标签: python loops iteration

我正在尝试遍历Python中的列表并获得平均值。例如,

A = [[3,4,6], [7,9,13], 'New York Jets']
  • A [0]代表胜利
  • A [1]代表损失
  • A [2]是团队

我想这样做:(3/10)+(4/13)+(6/19)

基本上,赢/(胜+亏)。这就是我试过的:

wins = A[0]
losses = A[1]

total = 0.0
for w,l in zip(wins, losses):
    total += float(w/(w+l))

不幸的是,这给了我错误的答案

2 个答案:

答案 0 :(得分:2)

>>> A = [[3,4,6], [7,9,13], 'New York Jets']
>>> [float(wins)/(wins+losses) for wins, losses in zip(*A[:2])]
[0.3, 0.3076923076923077, 0.3157894736842105]
>>> sum(float(wins)/(wins+losses) for wins, losses in zip(*A[:2]))
0.9234817813765183

答案 1 :(得分:2)

w / (w + l)已经是整数,因此将其传递给float不会有帮助。

要么使其中一个浮动:

float(w) / (w + 1)

或者在脚本顶部导入Python 3的分区,其中分割两个整数会导致浮动:

from __future__ import division

您可以执行以下操作:

averages = []

for wins, losses, team in teams:
    average = sum(win / float(win + loss) for win, loss in zip(wins, losses))

    averages.append(average)