基于条件聚合嵌套元组的结果

2024-04-20 00:56:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个嵌套的元组,我想得到一个有结果的表,我试图用理解这个,但我没有得到最好的结果。你知道吗

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

输出示例:

       first  second totalgoals
team1    1      2        3
team2    1      1        2

有人能帮我吗?你知道吗


Tags: 示例teamfirst元组second试图用team1team2
3条回答

这是一个纯基于Python字典的解决方案:

from operator import itemgetter

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

teams = map(itemgetter(1), lst)
d = {team: dict.fromkeys(('first', 'second', 'total'), 0) for team in teams}

for minutes, team in lst:
    if minutes <= 45:
        d[team]['first'] += 1
    else:
        d[team]['second'] += 1
    d[team]['total'] += 1

结果:

print(d)  

{'Team1': {'first': 1, 'second': 2, 'total': 3},
 'Team2': {'first': 1, 'second': 1, 'total': 2}}

您可以轻松地将简单的目标列表反转到按团队名称索引的字典中,并立即将上半部分和下半部分括起来,这样就不必对数据进行多次迭代,例如:

import collections

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

team_goals = collections.defaultdict(lambda: [0, 0])  # save some time with a dict factory
for entry in team:
    team_goals[entry[1]][entry[0] > 45] += 1

至于这是如何工作的,collections.defaultdict()将调用传递的工厂(lambda: [0, 0]),以便在遇到不存在的键时创建一个新键,因此每个团队将以[0, 0]列表作为其值开始。然后,当我们迭代数据时,我们只需要一个简单的entry[0] > 45检查作为索引选择器-in this context,它将被视为intFalse(因此是前半部分)和1True(因此是后半部分)生成0,从而使我们能够为增量选择适当的索引。你知道吗

这就产生了一个很好的字典,它的键包含了团队名称,而它的值本质上只是一个两元素的列表,用于计算上半部分和下半部分的目标。你知道吗

如果要打印数据,只需使用^{}即可获得所需的表外观,例如:

line_format = "{:<8} {:^5} {:^6} {:^10}"
print(line_format.format("", "first", "second", "totalgoals"))
for t, g in team_goals.items():
    print(line_format.format(t, g[0], g[1], sum(g)))

这将给你:

         first second totalgoals
Team1      1     2        3     
Team2      1     1        2   

作为额外的好处,为了更加整洁,您可以获得team_goals键的最大字符串长度,并根据您的团队数据动态填充左侧。你知道吗

你可以使用字典理解:

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

相关问题 更多 >