有什么方法可以在列表中为同一支球队加分?

时间:2019-04-23 11:01:24

标签: python arrays python-3.x list

如何为一个团队加分?

这是我尝试过的:

def check_league(league_points):
    league_results = []
    for teams in league_points:
    team, points = teams.strip().rsplit(' ', 1)
    print(team, points)

这是我的清单:

['Lions 1', 'Snakes 1', 'Tarantulas 3', 'FC Awesome 0', 'Lions 1', 'FC Awesome 1', 'Tarantulas 3', 'Snakes 0', 'Lions 3', 'Grouches 0']

输出:

('Lions', '1')

('Snakes', '1')

('Tarantulas', '3')

('FC Awesome', '0')

('Lions', '1')

('FC Awesome', '1')

('Tarantulas', '3')

('Snakes', '0')

('Lions', '3')
('Grouches', '0')

我希望输出为:

'Tarantulas', '6'

'Lions', '5'

'FC Awesome', '1'

'Snakes', '1'
'Grouches', '0'

3 个答案:

答案 0 :(得分:2)

itertools.groupbysorted一起使用:

import itertools

func = lambda x:x[0]
sorted_l = sorted([i.rsplit(' ', 1) for i in l], key=func)
{k: sum(map(int, list(zip(*g))[1])) for k, g in itertools.groupby(sorted_l, key=func)}

输出:

{'FC Awesome': 1, 'Grouches': 0, 'Lions': 5, 'Snakes': 1, 'Tarantulas': 6}

答案 1 :(得分:1)

您可以使用defaultdict并遍历列表中str.rsplit的项目:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> l = ['Lions 1', 'Snakes 1', 'Tarantulas 3', 'FC Awesome 0', 'Lions 1', 'FC Awesome 1', 'Tarantulas 3', 'Snakes 0', 'Lions 3', 'Grouches 0']
>>> for n, _, v in map(lambda s: s.rpartition(' '), l):
...     d[n] += int(v)
... 
>>> d
defaultdict(<class 'int'>, {'Lions': 5, 'Snakes': 1, 'Tarantulas': 6, 'FC Awesome': 1, 'Grouches': 0})

此算法在O(n)中运行,无需排序。

答案 2 :(得分:1)

我将字符串分成小组和分数,然后在我们创建字典的过程中。

li = ['Lions 1', 'Snakes 1', 'Tarantulas 3', 'FC Awesome 0', 'Lions 1', 'FC Awesome 1', 'Tarantulas 3', 'Snakes 0', 'Lions 3', 'Grouches 0']

dct = {}
for l in li:
    #Split only on last space
    name, count = l.rsplit(' ',1)
    if name in dct:
        dct[name] += int(count)
    else:
        dct[name] = int(count)

print(dct)
#{'Lions': 5, 'Snakes': 1, 'Tarantulas': 6, 'FC Awesome': 1, 'Grouches': 0}