简体   繁体   中英

Filter SQLAlchemy query with Python 3.5

I have the following code, which work correctly with Python 2.7, but raise exception with Python 3.5.1:

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)]

Trace:

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

I've seen the answer to similar question: TypeError: 'filter' object is not subscriptable , but it didn't help. How should I rewrite my code?

As it was mentioned in TypeError: 'filter' object is not subscriptable , in Python 2 filter returns a list, but in Python 3 filter returns an iterator. So I had to write:

next(filter(some code))

instead of:

filter(some code)[0]

So the valid code is:

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM