今天有个统计需求,需要对应的元素的列求和,文件示例如下:
1 ID1 0 2 7 2 ID2 1 5 6 3 ID3 2 2 6 4 ID4 1 6 0 5 ID2 3 8 3 6 ID2 0 8 3 7 ID4 2 2 9 8 ID2 3 7 7 9 ID1 1 5 3 10 ID2 2 3 7 11 ID3 0 2 5 12 ID2 5 4 7 13 ID4 5 8 2 14 ID2 6 9 9 15 ID1 1 4 4 16 ID2 8 2 9 17 ID1 1 3 0 18 ID3 8 0 3 19 ID2 9 2 9 20 ID4 1 5 6
求和代码如下:
1 import sys 2 dt=[] 3 dct={} 4 f=open(sys.argv[1],'r') 5 for i in f: 6 line=i.strip().split() 7 name=line[0] 8 dt=[int(x) for x in line[1:]] 9 dct.setdefault(name,[]).append(dt) 10 11 dct2=dict() 12 for each in dct: 13 cols=[] 14 for num in zip(*dct[each]): 15 cols.append(sum(num)) 16 dct2[each]=cols 17 18 for res in dct2: 19 info=" ".join([str(x) for x in dct2[res]]) 20 print(res+" "+info)
运行结果如下: