python 里的dict的问题
有4列数:
a;aaa;1;1
b;aaa;1;2
a;bbb;4;5
a;aaa;2;5
a;aaa;2;5
b;aaa;2;5
。。。后面还很多
怎么把第1列相同的数中的第2列相同的第3列求和,比如上面结果应该为:
a;aaa;5(1+2+2)#括号不显示
a;bbb;4
b;aaa;3
求教,谢谢
[解决办法]
lst1 = [ 'a;aaa;1;1', 'b;aaa;1;2', 'a;bbb;4;5', 'a;aaa;2;5', 'a;aaa;2;5', 'b;aaa;2;5' ]
dict1 = {}
for strLine in lst1 :
words = strLine.split( ';' )
key1 = words[0] + ';' + words[1]
value1 = int( words[2] )
if key1 in dict1:
dict1[key1] += value1
else :
dict1[key1] = value1
print dict1
file=open('1.txt','r')
strList=file.readlines()
dic=dict()
for line in strList:
if dic.get(line[0:6])==None:
dic[line[0:6]]=0
else:
dic[line[0:6]]+=int(line[6:8])
keys=dic.keys()
values=dic.values()
file=open('1.txt','w')
for i in range(len(keys)):
file.write(keys[i]+':'+values[i]+'\n')
file.close()