Created
August 31, 2018 08:00
-
-
Save timbledum/ede9a7045005e903809ccc63f0fb91ab to your computer and use it in GitHub Desktop.
Processing team scores
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> from collections import defaultdict | |
>>> data = """Lions 3, Snakes 3 | |
... Tarantulas 1, FC Awesome 0 | |
... Lions 1, FC Awesome 1 | |
... Tarantulas 3, Snakes 1 | |
... Lions 4, Grouches 0""" | |
>>> data_list = data.splitlines() | |
>>> data_list | |
['Lions 3, Snakes 3', 'Tarantulas 1, FC Awesome 0', 'Lions 1, FC Awesome 1', 'Tarantulas 3, Snakes 1', 'Lions 4, Grouches 0'] | |
>>> def splitter(row): | |
... left_team, right_team = row.split(',') | |
... return { | |
... "left": left_team[:-2].strip(), | |
... "lscore": int(left_team[-2:].strip()), | |
... "right": right_team[:-2].strip(), | |
... "rscore": int(right_team[-2:].strip()) | |
... } | |
... | |
... | |
>>> data_dicts = [splitter(row) for row in data_list] | |
>>> data_dicts | |
[{'left': 'Lions', 'lscore': 3, 'right': 'Snakes', 'rscore': 3}, {'left': 'Tarantulas', 'lscore': 1, 'right': 'FC Awesome', 'rscore': 0}, {'left': 'Lions', 'lscore': 1, 'right': 'FC Awesome', 'rscore': 1}, {'left': 'Tarantulas', 'lscore': 3, 'right': 'Snakes', 'rscore': 1}, {'left': 'Lions', 'lscore': 4, 'right': 'Grouches', 'rscore': 0}] | |
>>> team_scores = defaultdict(int) | |
>>> for game in data_dicts: | |
... if game['lscore'] == game['rscore']: | |
... team_scores[game['left']] += 1 | |
... team_scores[game['right']] += 1 | |
... elif game['lscore'] > game['rscore']: | |
... team_scores[game['left']] += 3 | |
... else: | |
... team_scores[game['right']] += 3 | |
... | |
>>> team_scores | |
defaultdict(<class 'int'>, {'Lions': 5, 'Snakes': 1, 'Tarantulas': 6, 'FC Awesome': 1}) | |
>>> teams_sorted = sorted(team_scores.items(), key=lambda team: team[1], reverse=True) | |
>>> teams_sorted | |
[('Tarantulas', 6), ('Lions', 5), ('Snakes', 1), ('FC Awesome', 1)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment