以下代码可以正常工作。但是,它可以在单个语句中完成三遍而不是调用player_apps吗?
for club in all_clubs:
total_app = sum(player['season_apps'] for player in players_apps if player['player_club'] == club)
total_sub_app = sum(player['season_sub_apps'] for player in players_apps if player['player_club'] == club)
total_goals = sum(player['season_goals'] for player in players_apps if player['player_club'] == club)
club_app_goal.append({'club' : club, 'total_app' : total_app, 'total_sub_app' : total_sub_app, 'total_goals' : total_goals})
答案 0 :(得分:0)
使用.
:
numpy
答案 1 :(得分:0)
嗯,从技术上讲,使用functools.reduce
是,但是它不会使代码更漂亮,而且我不确定它是否真的可以改善性能:
total_app, total_sub_app, total_goals = reduce(
lambda a, b: tuple(x + y for x, y in zip(a, b)),
((p['season_apps'], p['season_sub_apps'], p['season_goals']) for p in players_apps if p["club"] == club),
(0, 0, 0)
)
更有趣的“优化”恕我直言,每个俱乐部仅对球员进行一次过滤:
for club in all_clubs:
players = [player for player in players_apps if player['player_club'] == club]
total_app = sum(player['season_apps'] for player in players)
total_sub_app = sum(player['season_sub_apps'] for player in players)
total_goals = sum(player['season_goals'] for player in players)
更具可读性,甚至可能更快(取决于您的数据)。
话虽如此,使用适当的关系数据库(关系数据库是专门为这种计算而设计的)或至少使用Numpy或Panda,您可能会受益。