- 论坛徽章:
- 11
|
回复 1# 搁浅的思恋 - Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
- Type "copyright", "credits" or "license()" for more information.
- >>> some_file = '''
- A 1
- A 1
- A 2
- B 2
- C 2
- D 3
- E 4
- F 1
- G 1'''
- >>> from cStringIO import StringIO
- >>> from itertools import groupby
- >>> from collections import Counter
- >>> records = []
- >>> for line in StringIO(some_file):
- fields = line.strip().split()
- if len(fields) != 2:
- continue
- records.append([fields[0], int(fields[1], 10)])
-
- >>> records.sort(key=lambda v: (v[0], v[1])) #如果第一二列有序,省略之
- >>> for k1, g1 in groupby(records, key=lambda v: v[0]):
- cnt = Counter({k2: sum(1 for _ in g2)
- for k2, g2 in groupby(g1, key=lambda v: v[1])})
- v1, v2, v3, v4 = cnt[1], cnt[2], cnt[3], cnt[4]
- print k1, v1 + v2 + v3 + v4, v1, v2, v3, v4
-
- A 3 2 1 0 0
- B 1 0 1 0 0
- C 1 0 1 0 0
- D 1 0 0 1 0
- E 1 0 0 0 1
- F 1 1 0 0 0
- G 1 1 0 0 0
- >>>
复制代码 |
|