Thando
Thando

Reputation: 67

Is there a way I can add points together for the same team in a list?

How can I add the points together for one team?

This is what I have tried:

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

This is the list I have:

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

Output:

('Lions', '1')

('Snakes', '1')

('Tarantulas', '3')

('FC Awesome', '0')

('Lions', '1')

('FC Awesome', '1')

('Tarantulas', '3')

('Snakes', '0')

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

I want the output to be:

'Tarantulas', '6'

'Lions', '5'

'FC Awesome', '1'

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

Upvotes: 3

Views: 71

Answers (3)

Netwave
Netwave

Reputation: 42746

You can use defaultdict and iterate over the str.rsplit of the items in the list:

>>> 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})

This algorithm runs in O(n) without the need of sorting.

Upvotes: 1

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

I would split the string into teams and points, and then create a dictionary as we go.

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}

Upvotes: 1

Chris
Chris

Reputation: 29742

Use itertools.groupby with sorted:

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)}

Output:

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

Upvotes: 2

Related Questions