【问题标题】:python iterate over list in range of times and work out averagepython在时间范围内迭代列表并计算出平均值
【发布时间】:2017-03-07 13:22:45
【问题描述】:

这是代码将读取的输入 csv,其中包含团队名称

team_name   half_goals  FT_goals    shots   shots_on_target corners Result
Arsenal 1   1   16  4   4   L
Liverpool   1   1   26  11  12  W
Norwich 0   2   8   2   6   D
Sunderland  0   0   20  3   6   L
Swansea 0   1   17  6   7   L
West Brom   0   0   11  1   4   L
West Ham    1   2   18  4   4   W
Chelsea 2   2   22  5   5   W
Crystal Palace  0   0   5   3   3   L
Man City    2   4   20  11  8   W
Chelsea 1   2   15  3   1   W
Aston Villa 0   0   17  3   8   L
Everton 0   0   22  8   11  D
Fulham  0   1   16  7   1   L

这是我想阅读的代码,团队被提及次数然后计算出平均值

import csv
from datetime import datetime 
with open('League.csv','r') as csvfile:
    readCSV = csv.reader(csvfile,delimiter=',')
    next(readCSV)
    for row in readCSV:
        #print(row)
         lines = []
         lines.append(row)
         #print (lines)

         teams = set ()

         #print (teams)
         for line in lines :
                 home_team = line[2]
                 teams.add(home_team)

                 #print (teams)
                 for team in teams:
                         match = [line for line in lines if line[2]==team]
                         #print(match)

                         for i in range(5, len(match)):
                                history = match [i-5:i]
                                average = (history / 5)
                                print(average)

我想要做的是每 5 次在比赛中提到哪支球队的平均值。

期待输出

game 1-5 Team one ---  average
game 2-6 Team one ---  average
game 3-7 Team one ---  average

谢谢。

【问题讨论】:

  • 请先指定输入/预期输出...
  • 谢谢你,我已经这样做了......

标签: python list range average


【解决方案1】:

您正在使用 4 个嵌套的 for loops,请将您的代码简化为 一个 for loop。 关于您的问题:

我想要做的是每 5 次在比赛中提到哪支球队的平均值。

问:...每 5 次...:请在您的问题中说明,不能看到任何团队 5 次?
您想要 FT_goals 的平均值吗?
使用给定 csv 中的真实数据更新您的预期输出

【讨论】:

    猜你喜欢
    • 2019-11-09
    • 2018-02-28
    • 2020-11-09
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2021-08-21
    相关资源
    最近更新 更多