首页 > 解决方案 > Aggregating results from nested tuples based on conditions

问题描述

i have a nested tuple and i want to get a table with results, i'm trying to use comprehension on this but i'm not getting the best results.

team = ((35, 'Team1'),(8, 'Team2'),(55, 'Team1'),(65, 'Team2'),(90, 'Team1'))

output example:

       first  second totalgoals
team1    1      2        3
team2    1      1        2

Can anyone give me some help?

标签: pythontuples

解决方案


您可以使用字典理解:

team = ((35, 'Team1'),(8, 'Team2'),(55, 'Team1'),(65, 'Team2'),(90, 'Team1'))
results = {a:[sum(c < 45 and d == a for c, d in team), sum(c >= 45 and d == a for c, d in team)] for a in set(d for _, d in team)} 
print('\tfirst  second totalgoals')
for a, [first, second] in results.items():
  print(f'{a}\t{first}\t{second}\t{first+second}')

输出:

    first  second totalgoals
Team1   1   2   3
Team2   1   1   2

推荐阅读