字典的应用(根据第一列,统计第二列之和)
1 #-*- coding:utf-8 -*- 2 #根据第一列,统计和 3 4 ''' 5 cat info.txt 6 7 lisa,99 8 bart,80 9 lisa,100 10 bart,89 11 tom,87 12 13 ''' 14 15 d={} 16 with open('info.txt') as f: 17 for line in f: 18 line=line.strip().split(',') 19 if line[0] in d: 20 d[line[0]]+=int(line[1]) 21 else: 22 d[line[0]]=int(line[1]) 23 24 for k,v in d.items(): 25 print k,v 26