With combination of csv.reader
+ collections.defaultdict
+ collections.Counter
objects:
(结合使用csv.reader
+ collections.defaultdict
+ collections.Counter
对象:)
from collections import defaultdict, Counter
import csv
from io import StringIO
data = '''0 21 M 34 P
0 22 F 12 N
0 28 M 67 P
1 18 M 22 P
1 21 F 88 P
1 34 F 97 N
2 55 M 21 P
2 65 M 32 P
2 33 F 55 N
2 48 F 7 P'''
d = defaultdict(Counter)
reader = csv.reader(StringIO(data), skipinitialspace=True, delimiter=' ')
for row in reader:
d[row[0]][row[4]] += 1
d = {int(k): dict(v) for k, v in d.items()}
print(d)
The output:
(输出:)
{0: {'P': 2, 'N': 1}, 1: {'P': 2, 'N': 1}, 2: {'P': 3, 'N': 1}}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…