#判断元素出现的次数、总和
#coding:utf-8 d=[('a', 2), ('a', 1), ('b', 2), ('b', 5), ('c', 1), ('d', 5)] def main(): r ={} for a,b in d: t =r.get(a,{}) t['times']=t.get('times',0)+1 t['sum']=t.setdefault("sum",0)+b r[a]=t print r if __name__ == '__main__': main()
结果:
{'a': {'sum': 3, 'times': 2}, 'c': {'sum': 1, 'times': 1}, 'b': {'sum': 7, 'times': 2}, 'd': {'sum': 5, 'times': 1}}