python当中一个简单求和问题

文档如下1.txt
广州 15534 金钱1 1586
广州 15534 金钱2 15
广州 15537 金钱1 1583
广州 15537 金钱2 0
广州 15589 金钱1 153
广州 15589 金钱2 15
计算相同的编号的结果输出结果
广州 15534 金额1601
广州 15537 金额1583
广州 15537 金额168

用2.6写,越简单易懂越好,非常感谢。

#coding: utf-8
with open('1.txt','r') as f:
    d= {}
    for line in f:
        cityid = line.split(' ')[1]  #split是根据一个空格来分隔,你可以调整分隔
        num = int(line.split(' ')[-1])
        if  d.get(cityid):
            d[cityid] += num
        else:
            d[cityid] = num
    print d

温馨提示:答案为网友推荐,仅供参考
相似回答