2016-02-26 67 views
0

我有下面的代碼,這與Python 2.7正常工作,但與Python 3.5.1引發異常:過濾SQLAlchemy的查詢與Python 3.5

away_games = [{'home_team_results': filter(lambda x: x.team_id == g.home_team_id, g.team_stats)[0].as_dict(), 
       'away_team_results': filter(lambda x: x.team_id == g.visitor_team_id, g.team_stats)[0].as_dict()} 
       for g in self.db.query(Game).filter(Game.visitor_team == team).filter(Game.season == season)] 

跟蹤:

for g in self.db.query(Game).filter(Game.home_team == team).filter(Game.season == season)] 
TypeError: 'filter' object is not subscriptable 

我已經看到類似問題的答案:TypeError: 'filter' object is not subscriptable,但它沒有幫助。我應該如何重寫我的代碼?

回答

0

正如在TypeError: 'filter' object is not subscriptable中提到的那樣,在Python 2中過濾器返回一個列表,但在Python 3中過濾器返回一個迭代器。所以,我不得不寫:

next(filter(some code)) 

代替:

filter(some code)[0] 

所以有效的代碼是:

away_games = [{'home_team_results': next(filter(lambda x: x.team_id == g.home_team_id, g.team_stats)).as_dict(), 
       'away_team_results': next(filter(lambda x: x.team_id == g.visitor_team_id, g.team_stats)).as_dict()} 
       for g in self.db.query(Game).filter(Game.visitor_team == team).filter(Game.season == season)]