0

I have a class to represent NFL quarterbacks. In each instance will be a list of dictionaries, where each entry contains information regarding the QB stats for the game played. I need to generate the average number of yards gained per game based on all quarterbacks in my DB. I could easily do this outside of the object oriented structure by just looping through my instances, building a list, etc... but I think there must be some elegant way to do this object oriented style. So I'd like to build this function "get_avg", I will pass it the name of the variable I want the average from, like "get_avg('pass_yards')" or "get_avg('pass_attempt')" and it should return an average based on every instance, and every game in each instance, in existence.

class qb:
  def __init__(self, name, espn_player_id):
      self.name = name
      self.espn_player_id = espn_player_id
      self.games=[]

  def add_game(self, g):
      self.games.append(g)

  @classmethod
  def get_avg(cls, var):
     ##create one list based on each game entry in each instance and return average


qb_data = s.query(Box_Score).filter(Box_Score.pass_attempt>8).all()
seen = set()
qbs = [qb(g.player_name, g.espn_player_id) for g in qb_data if g.espn_player_id not in seen and not seen.add(g.espn_player_id)]

for q in qbs:
    for g in [qb_game for qb_game in qb_data if qb_game.espn_player_id==q.espn_player_id]:
        q.add_game({"date": g.date, "pass_attempt": g.pass_attempt, "pass_made": g.pass_made, "q_team": g.team_name, "opp_team": "",
                    "pass_yards": g.pass_yards, "pass_td": g.pass_td, "pass_int": g.pass_int, "pass_longest": g.pass_longest})

print qb.get_avg('pass_attempt')
print qb.get_avg('pass_td')
4

2 回答 2

2

你想做两件事:

  1. 创建一个类变量以包含您创建的所有四分卫。(我们称之为everyone
  2. 然后,在该__init__方法中,通过附加到该列表,将每个创建的四分卫添加self到该列表中。

然后,您可以在调用 get_avg 时对该列表进行求和和除法。

于 2013-10-03T21:56:20.843 回答
0

这是yan提供的解决方案

class qb:
    all_of_me =[]
    def __init__(self, name, espn_player_id):
        self.name = name
        self.espn_player_id = espn_player_id
        self.games=[]
        qb.all_of_me.append(self)

    def add_game(self, g):
        self.games.append(g)

    @classmethod
    def get_avg(cls, var):
        all_stats=[]
        for q in cls.all_of_me: all_stats.extend([n[var] for n in q.games])
        return np.mean(all_stats)
于 2013-10-03T22:12:59.720 回答