Rubyで点数を集計するとき、あなたはどうしてますか? をPythonで

Python でやってみた。

cf. Rubyで点数を集計するとき、あなたはどうしてますか? - hp12c

import re

class Score:
    def __init__(self, name, a, b):
        self.name = name
        self.a = a
        self.b = b

    def total(self):
        return self.a + self.b

data ="""player gameA gameB
Bob 20 56
Ross 68 33
Bob 78 55
Kent 90 15
Alice 84 79
Ross 10 15
Jimmy 80 31
Bob 12 36
Kent 88 43
Kent 12 33
Alice 90 32
Ross 67 77
Alice 56 92
Jimmy 33 88
Jimmy 11 87"""

a = re.split("\n", data)
headers = re.split("\s+", a[0])
values = map((lambda x: re.split("\s+", x)), a[1:])

scores = {}
for s in values:
    player = s[0]
    if player in scores:
        scores[player].a += int(s[1])
        scores[player].b += int(s[2])
    else:
        scores[player] = Score(player, int(s[1]), int(s[2]))

lanking = scores.values()
lanking.sort(lambda a,b: cmp(b.total(), a.total()))

print "%s\t%s\t%s\ttotal" % tuple(headers)
for player in lanking:
    print "%s\t%d\t%d\t%d" % (player.name, player.a, player.b, player.total())

実行結果:

^o^ > python game_score.py
player  gameA   gameB   total
Alice   230     203     433
Jimmy   124     206     330
Kent    190     91      281
Ross    145     125     270
Bob     110     147     257