0

我正在尝试遍历 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))

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

4

2 回答 2

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
于 2013-05-05T21:33:13.550 回答
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)
于 2013-05-05T21:33:33.067 回答