以下のような総当たり戦の結果表から、各playerの勝ち負けを集計したい場合がある。
(W:Win, L:Lose, D:draw)
test.csv
player1,-,L,L,W,L,L,L,W,L,W,W,
player2,W,-,W,W,L,L,L,W,L,L,W,
player3,W,L,-,W,L,L,W,L,L,W,W,
player4,L,L,L,-,W,W,L,L,L,L,W,
player5,W,W,W,L,-,D,L,L,L,W,W,
player6,W,W,W,L,D,-,L,L,W,L,W,
player7,W,W,L,W,W,W,-,L,L,L,W,
player8,L,L,W,W,W,W,W,-,D,W,W,
player9,W,W,W,W,W,L,W,D,-,W,W,
player10,L,W,L,W,L,W,W,L,L,-,W,
player11,L,L,L,L,L,L,L,L,L,L,-,
以下のような出力が期待値
Player,W,L,D
player9,8,1,1
player8,7,2,1
player7,6,4,0
player2,5,5,0
player3,5,5,0
player10,5,5,0
player5,5,4,1
player6,5,4,1
player1,4,6,0
player4,3,7,0
player11,0,10,0
これを処理するには以下のようなスクリプトを実行すればOK
test.py
import sys
ll=[]
# 入力
for line in sys.stdin.readlines():
A=list(map(str, line.split(',')))
ll.append(A)
# count
l_out=[]
for l in ll:
PLAYER=l[0]
W_NUM=l[1:].count('W')
L_NUM=l[1:].count('L')
D_NUM=l[1:].count('D')
l_out.append([PLAYER,W_NUM,L_NUM,D_NUM])
# sort
l_out.sort(key=lambda val: val[3], reverse=True)
l_out.sort(key=lambda val: val[2], reverse=True)
l_out.sort(key=lambda val: val[1], reverse=True)
print("Player,W,L,D")
for l in l_out:
print(*l, sep=',')
実行結果
$ cat test.csv | python3 test.py
Player,W,L,D
player9,8,1,1
player8,7,2,1
player7,6,4,0
player2,5,5,0
player3,5,5,0
player10,5,5,0
player5,5,4,1
player6,5,4,1
player1,4,6,0
player4,3,7,0
player11,0,10,0
markdownの表に変換したい場合は以下の通り
$ cat test.csv | python3 test.py | csvtomd
Player | W | L | D |
---|---|---|---|
player9 | 8 | 1 | 1 |
player8 | 7 | 2 | 1 |
player7 | 6 | 4 | 0 |
player2 | 5 | 5 | 0 |
player3 | 5 | 5 | 0 |
player10 | 5 | 5 | 0 |
player5 | 5 | 4 | 1 |
player6 | 5 | 4 | 1 |
player1 | 4 | 6 | 0 |
player4 | 3 | 7 | 0 |
player11 | 0 | 10 | 0 |
以上です
参考