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
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,它将被视为int为False(因此是前半部分)和1为True(因此是后半部分)生成0,从而使我们能够为增量选择适当的索引。你知道吗
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}')
这是一个纯基于Python字典的解决方案:
结果:
您可以轻松地将简单的目标列表反转到按团队名称索引的字典中,并立即将上半部分和下半部分括起来,这样就不必对数据进行多次迭代,例如:
至于这是如何工作的,
collections.defaultdict()
将调用传递的工厂(lambda: [0, 0]
),以便在遇到不存在的键时创建一个新键,因此每个团队将以[0, 0]
列表作为其值开始。然后,当我们迭代数据时,我们只需要一个简单的entry[0] > 45
检查作为索引选择器-in this context,它将被视为int
为False
(因此是前半部分)和1
为True
(因此是后半部分)生成0
,从而使我们能够为增量选择适当的索引。你知道吗这就产生了一个很好的字典,它的键包含了团队名称,而它的值本质上只是一个两元素的列表,用于计算上半部分和下半部分的目标。你知道吗
如果要打印数据,只需使用^{} 即可获得所需的表外观,例如:
这将给你:
作为额外的好处,为了更加整洁,您可以获得
team_goals
键的最大字符串长度,并根据您的团队数据动态填充左侧。你知道吗你可以使用字典理解:
输出:
相关问题 更多 >
编程相关推荐